--- a/.hgtags Mon May 05 12:48:07 2014 -0700
+++ b/.hgtags Mon May 12 09:37:50 2014 -0700
@@ -254,3 +254,4 @@
efe7dbc6088691757404e0c8745f894e3ca9c022 jdk9-b09
8c0bdeecd7c0f9ce3f3762a51991f755cb3a972c jdk9-b10
0809c9a4d36e6291f1c4384604c4bbf29e975722 jdk9-b11
+0d1f816217dce5e72187f167cc1816080cbeb453 jdk9-b12
--- a/.hgtags-top-repo Mon May 05 12:48:07 2014 -0700
+++ b/.hgtags-top-repo Mon May 12 09:37:50 2014 -0700
@@ -254,3 +254,4 @@
4a21dc7d57d1069a01f68e7182c074cb37349dfb jdk9-b09
fa13f2b926f8426876ec03e7903f3ee0ee150f2e jdk9-b10
ab55a18a95e1990a588929d5d29db3eb9985fea0 jdk9-b11
+59f6350295f9681fe5956d8bc889bf341914c6cb jdk9-b12
--- a/common/bin/hgforest.sh Mon May 05 12:48:07 2014 -0700
+++ b/common/bin/hgforest.sh Mon May 12 09:37:50 2014 -0700
@@ -144,8 +144,10 @@
repos="${repos} ${i}"
fi
done
+
+ pull_default_tail=`echo ${pull_default} | sed -e 's@^.*://[^/]*/\(.*\)@\1@'`
+
if [ "${command_args}" != "" ] ; then
- pull_default_tail=`echo ${pull_default} | sed -e 's@^.*://[^/]*/\(.*\)@\1@'`
if [ "x${pull_default}" = "x${pull_default_tail}" ] ; then
echo "ERROR: Need initial clone from non-local source" > ${status_output}
exit 1
@@ -156,6 +158,16 @@
repos_extra="${repos_extra} ${i}"
fi
done
+ else
+ if [ "x${pull_default}" = "x${pull_default_tail}" ] ; then
+ # local source repo. Copy the extras ones that exist there.
+ for i in ${subrepos_extra} ; do
+ if [ -f ${pull_default}/${i}/.hg/hgrc -a ! -f ${i}/.hg/hgrc ] ; then
+ # sub-repo there in source but not here
+ repos_extra="${repos_extra} ${i}"
+ fi
+ done
+ fi
fi
at_a_time=2
# Any repos to deal with?
--- a/corba/.hgtags Mon May 05 12:48:07 2014 -0700
+++ b/corba/.hgtags Mon May 12 09:37:50 2014 -0700
@@ -254,3 +254,4 @@
1a3a4f48515dbf1cff37279691b2fb74f228298d jdk9-b09
3bd4039dfc632fd7fc8418a25a3dcc34d1cd4019 jdk9-b10
77ea0a2503582a28e4e66be7239a49a0d1dd313f jdk9-b11
+e212cdcc8c11f0ba5acf6f5ddb596c4c545a93f9 jdk9-b12
--- a/hotspot/.hgtags Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/.hgtags Mon May 12 09:37:50 2014 -0700
@@ -414,3 +414,4 @@
05e8f5242c26ba45d4fa947e4f4f54c058c9b522 jdk9-b09
ebc44d040cd149d2120d69fe183a3dae7840f4b4 jdk9-b10
783309c3a1a629a452673399dcfa83ef7eca94d8 jdk9-b11
+1c383bb39e2849ca62cb763f4e182a29b421d60a jdk9-b12
--- a/hotspot/make/aix/makefiles/buildtree.make Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/aix/makefiles/buildtree.make Mon May 12 09:37:50 2014 -0700
@@ -37,7 +37,7 @@
# GAMMADIR - top of workspace
# OS_FAMILY - operating system
# VARIANT - core, compiler1, compiler2, or tiered
-# HOTSPOT_RELEASE_VERSION - <major>.<minor>-b<nn> (11.0-b07)
+# HOTSPOT_RELEASE_VERSION - <major_ver>.<minor_ver>.<micro_ver>[-<identifier>][-<debug_target>][-b<nn>]
# HOTSPOT_BUILD_VERSION - internal, internal-$(USER_RELEASE_SUFFIX) or empty
# JRE_RELEASE_VERSION - <major>.<minor>.<micro> (1.7.0)
#
--- a/hotspot/make/aix/makefiles/mapfile-vers-debug Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/aix/makefiles/mapfile-vers-debug Mon May 12 09:37:50 2014 -0700
@@ -122,7 +122,7 @@
JVM_GetClassModifiers;
JVM_GetClassName;
JVM_GetClassNameUTF;
- JVM_GetClassSignature;
+ JVM_GetClassSignature;
JVM_GetClassSigners;
JVM_GetClassTypeAnnotations;
JVM_GetComponentType;
@@ -163,6 +163,7 @@
JVM_GetStackTraceElement;
JVM_GetSystemPackage;
JVM_GetSystemPackages;
+ JVM_GetTemporaryDirectory;
JVM_GetThreadStateNames;
JVM_GetThreadStateValues;
JVM_GetVersionInfo;
--- a/hotspot/make/aix/makefiles/mapfile-vers-product Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/aix/makefiles/mapfile-vers-product Mon May 12 09:37:50 2014 -0700
@@ -161,6 +161,7 @@
JVM_GetStackTraceElement;
JVM_GetSystemPackage;
JVM_GetSystemPackages;
+ JVM_GetTemporaryDirectory;
JVM_GetThreadStateNames;
JVM_GetThreadStateValues;
JVM_GetVersionInfo;
--- a/hotspot/make/aix/makefiles/vm.make Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/aix/makefiles/vm.make Mon May 12 09:37:50 2014 -0700
@@ -73,17 +73,14 @@
endif
endif
-# HOTSPOT_RELEASE_VERSION and HOTSPOT_BUILD_VERSION are defined
-# in $(GAMMADIR)/make/defs.make
-ifeq ($(HOTSPOT_BUILD_VERSION),)
- BUILD_VERSION = -DHOTSPOT_RELEASE_VERSION="\"$(HOTSPOT_RELEASE_VERSION)\""
-else
- BUILD_VERSION = -DHOTSPOT_RELEASE_VERSION="\"$(HOTSPOT_RELEASE_VERSION)-$(HOTSPOT_BUILD_VERSION)\""
-endif
-
# The following variables are defined in the generated flags.make file.
-BUILD_VERSION = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\""
-JRE_VERSION = -DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\""
+JDK_VER_DEFS = -DJDK_MAJOR_VERSION="\"$(JDK_MAJOR_VERSION)\"" \
+ -DJDK_MINOR_VERSION="\"$(JDK_MINOR_VERSION)\"" \
+ -DJDK_MICRO_VERSION="\"$(JDK_MICRO_VERSION)\"" \
+ -DJDK_BUILD_NUMBER="\"$(JDK_BUILD_NUMBER)\""
+VM_VER_DEFS = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\"" \
+ -DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\"" \
+ $(JDK_VER_DEFS)
HS_LIB_ARCH = -DHOTSPOT_LIB_ARCH=\"$(LIBARCH)\"
BUILD_TARGET = -DHOTSPOT_BUILD_TARGET="\"$(TARGET)\""
BUILD_USER = -DHOTSPOT_BUILD_USER="\"$(HOTSPOT_BUILD_USER)\""
@@ -92,7 +89,6 @@
CXXFLAGS = \
${SYSDEFS} \
${INCLUDES} \
- ${BUILD_VERSION} \
${BUILD_TARGET} \
${BUILD_USER} \
${HS_LIB_ARCH} \
@@ -101,7 +97,7 @@
# This is VERY important! The version define must only be supplied to vm_version.o
# If not, ccache will not re-use the cache at all, since the version string might contain
# a time and date.
-CXXFLAGS/vm_version.o += ${JRE_VERSION}
+CXXFLAGS/vm_version.o += ${VM_VER_DEFS}
CXXFLAGS/BYFILE = $(CXXFLAGS/$@)
--- a/hotspot/make/bsd/makefiles/buildtree.make Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/bsd/makefiles/buildtree.make Mon May 12 09:37:50 2014 -0700
@@ -36,7 +36,7 @@
# GAMMADIR - top of workspace
# OS_FAMILY - operating system
# VARIANT - core, compiler1, compiler2, or tiered
-# HOTSPOT_RELEASE_VERSION - <major>.<minor>-b<nn> (11.0-b07)
+# HOTSPOT_RELEASE_VERSION - <major_ver>.<minor_ver>.<micro_ver>[-<identifier>][-<debug_target>][-b<nn>]
# HOTSPOT_BUILD_VERSION - internal, internal-$(USER_RELEASE_SUFFIX) or empty
# JRE_RELEASE_VERSION - <major>.<minor>.<micro> (1.7.0)
#
--- a/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug Mon May 12 09:37:50 2014 -0700
@@ -161,6 +161,7 @@
_JVM_GetStackTraceElement
_JVM_GetSystemPackage
_JVM_GetSystemPackages
+ _JVM_GetTemporaryDirectory
_JVM_GetThreadStateNames
_JVM_GetThreadStateValues
_JVM_GetVersionInfo
--- a/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product Mon May 12 09:37:50 2014 -0700
@@ -161,6 +161,7 @@
_JVM_GetStackTraceElement
_JVM_GetSystemPackage
_JVM_GetSystemPackages
+ _JVM_GetTemporaryDirectory
_JVM_GetThreadStateNames
_JVM_GetThreadStateValues
_JVM_GetVersionInfo
--- a/hotspot/make/bsd/makefiles/mapfile-vers-debug Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-debug Mon May 12 09:37:50 2014 -0700
@@ -122,7 +122,7 @@
JVM_GetClassModifiers;
JVM_GetClassName;
JVM_GetClassNameUTF;
- JVM_GetClassSignature;
+ JVM_GetClassSignature;
JVM_GetClassSigners;
JVM_GetClassTypeAnnotations;
JVM_GetComponentType;
@@ -163,6 +163,7 @@
JVM_GetStackTraceElement;
JVM_GetSystemPackage;
JVM_GetSystemPackages;
+ JVM_GetTemporaryDirectory;
JVM_GetThreadStateNames;
JVM_GetThreadStateValues;
JVM_GetVersionInfo;
--- a/hotspot/make/bsd/makefiles/mapfile-vers-product Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-product Mon May 12 09:37:50 2014 -0700
@@ -163,6 +163,7 @@
JVM_GetStackTraceElement;
JVM_GetSystemPackage;
JVM_GetSystemPackages;
+ JVM_GetTemporaryDirectory;
JVM_GetThreadStateNames;
JVM_GetThreadStateValues;
JVM_GetVersionInfo;
--- a/hotspot/make/bsd/makefiles/vm.make Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/bsd/makefiles/vm.make Mon May 12 09:37:50 2014 -0700
@@ -72,17 +72,14 @@
endif
endif
-# HOTSPOT_RELEASE_VERSION and HOTSPOT_BUILD_VERSION are defined
-# in $(GAMMADIR)/make/defs.make
-ifeq ($(HOTSPOT_BUILD_VERSION),)
- BUILD_VERSION = -DHOTSPOT_RELEASE_VERSION="\"$(HOTSPOT_RELEASE_VERSION)\""
-else
- BUILD_VERSION = -DHOTSPOT_RELEASE_VERSION="\"$(HOTSPOT_RELEASE_VERSION)-$(HOTSPOT_BUILD_VERSION)\""
-endif
-
# The following variables are defined in the generated flags.make file.
-BUILD_VERSION = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\""
-JRE_VERSION = -DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\""
+JDK_VER_DEFS = -DJDK_MAJOR_VERSION="\"$(JDK_MAJOR_VERSION)\"" \
+ -DJDK_MINOR_VERSION="\"$(JDK_MINOR_VERSION)\"" \
+ -DJDK_MICRO_VERSION="\"$(JDK_MICRO_VERSION)\"" \
+ -DJDK_BUILD_NUMBER="\"$(JDK_BUILD_NUMBER)\""
+VM_VER_DEFS = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\"" \
+ -DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\"" \
+ $(JDK_VER_DEFS)
HS_LIB_ARCH = -DHOTSPOT_LIB_ARCH=\"$(LIBARCH)\"
BUILD_TARGET = -DHOTSPOT_BUILD_TARGET="\"$(TARGET)\""
BUILD_USER = -DHOTSPOT_BUILD_USER="\"$(HOTSPOT_BUILD_USER)\""
@@ -91,7 +88,6 @@
CXXFLAGS = \
${SYSDEFS} \
${INCLUDES} \
- ${BUILD_VERSION} \
${BUILD_TARGET} \
${BUILD_USER} \
${HS_LIB_ARCH} \
@@ -100,7 +96,7 @@
# This is VERY important! The version define must only be supplied to vm_version.o
# If not, ccache will not re-use the cache at all, since the version string might contain
# a time and date.
-CXXFLAGS/vm_version.o += ${JRE_VERSION}
+CXXFLAGS/vm_version.o += ${VM_VER_DEFS}
CXXFLAGS/BYFILE = $(CXXFLAGS/$@)
--- a/hotspot/make/defs.make Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/defs.make Mon May 12 09:37:50 2014 -0700
@@ -114,7 +114,7 @@
endif
# hotspot version definitions
-include $(GAMMADIR)/make/hotspot_version
+include $(GAMMADIR)/make/jdk_version
# Java versions needed
ifeq ($(PREVIOUS_JDK_VERSION),)
@@ -129,6 +129,9 @@
ifeq ($(JDK_MICRO_VERSION),)
JDK_MICRO_VERSION=$(JDK_MICRO_VER)
endif
+ifeq ($(JDK_BUILD_NUMBER),)
+ JDK_BUILD_NUMBER=0
+endif
ifeq ($(JDK_MKTG_VERSION),)
JDK_MKTG_VERSION=$(JDK_MINOR_VERSION).$(JDK_MICRO_VERSION)
endif
@@ -146,7 +149,7 @@
endif
ifndef HOTSPOT_RELEASE_VERSION
- HOTSPOT_RELEASE_VERSION=$(HS_MAJOR_VER).$(HS_MINOR_VER)-b$(HS_BUILD_NUMBER)
+ HOTSPOT_RELEASE_VERSION=$(FULL_VERSION)
endif
ifdef HOTSPOT_BUILD_VERSION
@@ -325,7 +328,6 @@
MAKE_ARGS += OUTPUTDIR=$(ABS_OUTPUTDIR)
MAKE_ARGS += GAMMADIR=$(ABS_GAMMADIR)
MAKE_ARGS += MAKE_VERBOSE=$(MAKE_VERBOSE)
-MAKE_ARGS += HOTSPOT_RELEASE_VERSION=$(HOTSPOT_RELEASE_VERSION)
MAKE_ARGS += JRE_RELEASE_VERSION=$(JRE_RELEASE_VERSION)
# Pass HOTSPOT_BUILD_VERSION as argument to OS specific Makefile
--- a/hotspot/make/hotspot_version Mon May 05 12:48:07 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,45 +0,0 @@
-#
-# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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.
-#
-
-#
-#
-
-#
-# Master Hotspot version file. These values may be overridden by a control
-# workspace build. This file format must remain compatible with both
-# GNU Makefile and Microsoft nmake formats.
-#
-
-# Don't put quotes (fail windows build).
-HOTSPOT_VM_COPYRIGHT=Copyright 2013
-
-HS_MAJOR_VER=25
-HS_MINOR_VER=0
-HS_BUILD_NUMBER=62
-
-JDK_MAJOR_VER=1
-JDK_MINOR_VER=8
-JDK_MICRO_VER=0
-
-# Previous (bootdir) JDK version
-JDK_PREVIOUS_VERSION=1.7.0
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/make/jdk_version Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,36 @@
+#
+# 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
+# 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.
+#
+# Master JDK version file. These values may be overridden by a control
+# workspace build. This file format must remain compatible with both
+# GNU Makefile and Microsoft nmake formats.
+#
+
+# Don't put quotes (fail windows build).
+HOTSPOT_VM_COPYRIGHT=Copyright 2014
+
+JDK_MAJOR_VER=1
+JDK_MINOR_VER=9
+JDK_MICRO_VER=0
+
+# Previous (bootdir) JDK version
+JDK_PREVIOUS_VERSION=1.8.0
--- a/hotspot/make/linux/makefiles/buildtree.make Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/linux/makefiles/buildtree.make Mon May 12 09:37:50 2014 -0700
@@ -36,7 +36,7 @@
# GAMMADIR - top of workspace
# OS_FAMILY - operating system
# VARIANT - core, compiler1, compiler2, or tiered
-# HOTSPOT_RELEASE_VERSION - <major>.<minor>-b<nn> (11.0-b07)
+# HOTSPOT_RELEASE_VERSION - <major_ver>.<minor_ver>.<micro_ver>[-<identifier>][-<debug_target>][-b<nn>]
# HOTSPOT_BUILD_VERSION - internal, internal-$(USER_RELEASE_SUFFIX) or empty
# JRE_RELEASE_VERSION - <major>.<minor>.<micro> (1.7.0)
#
--- a/hotspot/make/linux/makefiles/mapfile-vers-debug Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/linux/makefiles/mapfile-vers-debug Mon May 12 09:37:50 2014 -0700
@@ -122,7 +122,7 @@
JVM_GetClassModifiers;
JVM_GetClassName;
JVM_GetClassNameUTF;
- JVM_GetClassSignature;
+ JVM_GetClassSignature;
JVM_GetClassSigners;
JVM_GetClassTypeAnnotations;
JVM_GetComponentType;
@@ -163,6 +163,7 @@
JVM_GetStackTraceElement;
JVM_GetSystemPackage;
JVM_GetSystemPackages;
+ JVM_GetTemporaryDirectory;
JVM_GetThreadStateNames;
JVM_GetThreadStateValues;
JVM_GetVersionInfo;
--- a/hotspot/make/linux/makefiles/mapfile-vers-product Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/linux/makefiles/mapfile-vers-product Mon May 12 09:37:50 2014 -0700
@@ -163,6 +163,7 @@
JVM_GetStackTraceElement;
JVM_GetSystemPackage;
JVM_GetSystemPackages;
+ JVM_GetTemporaryDirectory;
JVM_GetThreadStateNames;
JVM_GetThreadStateValues;
JVM_GetVersionInfo;
--- a/hotspot/make/linux/makefiles/vm.make Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/linux/makefiles/vm.make Mon May 12 09:37:50 2014 -0700
@@ -73,17 +73,14 @@
endif
endif
-# HOTSPOT_RELEASE_VERSION and HOTSPOT_BUILD_VERSION are defined
-# in $(GAMMADIR)/make/defs.make
-ifeq ($(HOTSPOT_BUILD_VERSION),)
- BUILD_VERSION = -DHOTSPOT_RELEASE_VERSION="\"$(HOTSPOT_RELEASE_VERSION)\""
-else
- BUILD_VERSION = -DHOTSPOT_RELEASE_VERSION="\"$(HOTSPOT_RELEASE_VERSION)-$(HOTSPOT_BUILD_VERSION)\""
-endif
-
# The following variables are defined in the generated flags.make file.
-BUILD_VERSION = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\""
-JRE_VERSION = -DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\""
+JDK_VER_DEFS = -DJDK_MAJOR_VERSION="\"$(JDK_MAJOR_VERSION)\"" \
+ -DJDK_MINOR_VERSION="\"$(JDK_MINOR_VERSION)\"" \
+ -DJDK_MICRO_VERSION="\"$(JDK_MICRO_VERSION)\"" \
+ -DJDK_BUILD_NUMBER="\"$(JDK_BUILD_NUMBER)\""
+VM_VER_DEFS = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\"" \
+ -DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\"" \
+ $(JDK_VER_DEFS)
HS_LIB_ARCH = -DHOTSPOT_LIB_ARCH=\"$(LIBARCH)\"
BUILD_TARGET = -DHOTSPOT_BUILD_TARGET="\"$(TARGET)\""
BUILD_USER = -DHOTSPOT_BUILD_USER="\"$(HOTSPOT_BUILD_USER)\""
@@ -92,7 +89,6 @@
CXXFLAGS = \
${SYSDEFS} \
${INCLUDES} \
- ${BUILD_VERSION} \
${BUILD_TARGET} \
${BUILD_USER} \
${HS_LIB_ARCH} \
@@ -101,7 +97,7 @@
# This is VERY important! The version define must only be supplied to vm_version.o
# If not, ccache will not re-use the cache at all, since the version string might contain
# a time and date.
-CXXFLAGS/vm_version.o += ${JRE_VERSION}
+CXXFLAGS/vm_version.o += ${VM_VER_DEFS}
CXXFLAGS/BYFILE = $(CXXFLAGS/$@)
--- a/hotspot/make/solaris/makefiles/buildtree.make Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/solaris/makefiles/buildtree.make Mon May 12 09:37:50 2014 -0700
@@ -36,7 +36,7 @@
# GAMMADIR - top of workspace
# OS_FAMILY - operating system
# VARIANT - core, compiler1, compiler2, or tiered
-# HOTSPOT_RELEASE_VERSION - <major>.<minor>-b<nn> (11.0-b07)
+# HOTSPOT_RELEASE_VERSION - <major_ver>.<minor_ver>.<micro_ver>[-<identifier>][-<debug_target>][-b<nn>]
# HOTSPOT_BUILD_VERSION - internal, internal-$(USER_RELEASE_SUFFIX) or empty
# JRE_RELEASE_VERSION - <major>.<minor>.<micro> (1.7.0)
#
--- a/hotspot/make/solaris/makefiles/mapfile-vers Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/solaris/makefiles/mapfile-vers Mon May 12 09:37:50 2014 -0700
@@ -163,6 +163,7 @@
JVM_GetStackTraceElement;
JVM_GetSystemPackage;
JVM_GetSystemPackages;
+ JVM_GetTemporaryDirectory;
JVM_GetThreadStateNames;
JVM_GetThreadStateValues;
JVM_GetVersionInfo;
--- a/hotspot/make/solaris/makefiles/vm.make Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/solaris/makefiles/vm.make Mon May 12 09:37:50 2014 -0700
@@ -69,8 +69,13 @@
endif
# The following variables are defined in the generated flags.make file.
-BUILD_VERSION = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\""
-JRE_VERSION = -DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\""
+JDK_VER_DEFS = -DJDK_MAJOR_VERSION="\"$(JDK_MAJOR_VERSION)\"" \
+ -DJDK_MINOR_VERSION="\"$(JDK_MINOR_VERSION)\"" \
+ -DJDK_MICRO_VERSION="\"$(JDK_MICRO_VERSION)\"" \
+ -DJDK_BUILD_NUMBER="\"$(JDK_BUILD_NUMBER)\""
+VM_VER_DEFS = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\"" \
+ -DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\"" \
+ $(JDK_VER_DEFS)
HS_LIB_ARCH = -DHOTSPOT_LIB_ARCH=\"$(LIBARCH)\"
BUILD_TARGET = -DHOTSPOT_BUILD_TARGET="\"$(TARGET)\""
BUILD_USER = -DHOTSPOT_BUILD_USER="\"$(HOTSPOT_BUILD_USER)\""
@@ -79,7 +84,6 @@
CXXFLAGS = \
${SYSDEFS} \
${INCLUDES} \
- ${BUILD_VERSION} \
${BUILD_TARGET} \
${BUILD_USER} \
${HS_LIB_ARCH} \
@@ -88,7 +92,7 @@
# This is VERY important! The version define must only be supplied to vm_version.o
# If not, ccache will not re-use the cache at all, since the version string might contain
# a time and date.
-CXXFLAGS/vm_version.o += ${JRE_VERSION}
+CXXFLAGS/vm_version.o += ${VM_VER_DEFS}
CXXFLAGS/BYFILE = $(CXXFLAGS/$@)
--- a/hotspot/make/windows/build.make Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/windows/build.make Mon May 12 09:37:50 2014 -0700
@@ -117,7 +117,7 @@
# These can be overridden via the nmake.exe command line.
# They are overridden by RE during the control builds.
#
-!include "$(WorkSpace)/make/hotspot_version"
+!include "$(WorkSpace)/make/jdk_version"
# Define HOTSPOT_VM_DISTRO based on settings in make/openjdk_distro
# or make/hotspot_distro.
@@ -163,7 +163,7 @@
# 1.6.0-b01 will be 6.0.0.1
# 1.6.0_01a-b02 will be 6.0.11.2
#
-# JDK_* variables are defined in make/hotspot_version or on command line
+# JDK_* variables are defined in make/jdk_version or on command line
#
JDK_VER=$(JDK_MINOR_VER),$(JDK_MICRO_VER),$(JDK_UPDATE_VER),$(JDK_BUILD_NUMBER)
JDK_DOTVER=$(JDK_MINOR_VER).$(JDK_MICRO_VER).$(JDK_UPDATE_VER).$(JDK_BUILD_NUMBER)
@@ -179,13 +179,12 @@
# Hotspot Express VM FileVersion:
# 10.0-b<yz> will have DLL version 10.0.0.yz (need 4 numbers).
#
-# HS_* variables are defined in make/hotspot_version
#
-HS_VER=$(HS_MAJOR_VER),$(HS_MINOR_VER),0,$(HS_BUILD_NUMBER)
-HS_DOTVER=$(HS_MAJOR_VER).$(HS_MINOR_VER).0.$(HS_BUILD_NUMBER)
+HS_VER=$(JDK_VER)
+HS_DOTVER=$(JDK_DOTVER)
!if "$(HOTSPOT_RELEASE_VERSION)" == ""
-HOTSPOT_RELEASE_VERSION=$(HS_MAJOR_VER).$(HS_MINOR_VER)-b$(HS_BUILD_NUMBER)
+HOTSPOT_RELEASE_VERSION=$(JRE_RELEASE_VERSION)
!endif
!if "$(HOTSPOT_BUILD_VERSION)" == ""
--- a/hotspot/make/windows/makefiles/defs.make Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/windows/makefiles/defs.make Mon May 12 09:37:50 2014 -0700
@@ -179,9 +179,9 @@
# next parameters are defined in $(GAMMADIR)/make/defs.make.
MAKE_ARGS += JDK_MKTG_VERSION=$(JDK_MKTG_VERSION)
-MAKE_ARGS += JDK_MAJOR_VER=$(JDK_MAJOR_VERSION)
-MAKE_ARGS += JDK_MINOR_VER=$(JDK_MINOR_VERSION)
-MAKE_ARGS += JDK_MICRO_VER=$(JDK_MICRO_VERSION)
+MAKE_ARGS += JDK_MAJOR_VERSION=$(JDK_MAJOR_VERSION)
+MAKE_ARGS += JDK_MINOR_VERSION=$(JDK_MINOR_VERSION)
+MAKE_ARGS += JDK_MICRO_VERSION=$(JDK_MICRO_VERSION)
ifdef COOKED_JDK_UPDATE_VERSION
MAKE_ARGS += JDK_UPDATE_VER=$(COOKED_JDK_UPDATE_VERSION)
--- a/hotspot/make/windows/makefiles/vm.make Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/windows/makefiles/vm.make Mon May 12 09:37:50 2014 -0700
@@ -56,6 +56,10 @@
# The following variables are defined in the generated local.make file.
CXX_FLAGS=$(CXX_FLAGS) /D "HOTSPOT_RELEASE_VERSION=\"$(HS_BUILD_VER)\""
+CXX_FLAGS=$(CXX_FLAGS) /D "JDK_MAJOR_VERSION=\"$(JDK_MAJOR_VERSION)\""
+CXX_FLAGS=$(CXX_FLAGS) /D "JDK_MINOR_VERSION=\"$(JDK_MINOR_VERSION)\""
+CXX_FLAGS=$(CXX_FLAGS) /D "JDK_MICRO_VERSION=\"$(JDK_MICRO_VERSION)\""
+CXX_FLAGS=$(CXX_FLAGS) /D "JDK_BUILD_NUMBER=\"$(JDK_BUILD_NUMBER)\""
CXX_FLAGS=$(CXX_FLAGS) /D "JRE_RELEASE_VERSION=\"$(JRE_RELEASE_VER)\""
CXX_FLAGS=$(CXX_FLAGS) /D "HOTSPOT_LIB_ARCH=\"$(HOTSPOT_LIB_ARCH)\""
CXX_FLAGS=$(CXX_FLAGS) /D "HOTSPOT_BUILD_TARGET=\"$(BUILD_FLAVOR)\""
--- a/hotspot/make/windows/projectfiles/common/Makefile Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/make/windows/projectfiles/common/Makefile Mon May 12 09:37:50 2014 -0700
@@ -78,24 +78,23 @@
default:: $(AdditionalTargets) $(JvmtiGeneratedFiles) $(TraceGeneratedFiles)
-!include $(HOTSPOTWORKSPACE)/make/hotspot_version
+!include $(HOTSPOTWORKSPACE)/make/jdk_version
!if "$(USER_RELEASE_SUFFIX)" != ""
HOTSPOT_BUILD_VERSION = internal-$(USER_RELEASE_SUFFIX)
!else
HOTSPOT_BUILD_VERSION = internal
!endif
-!if "$(HOTSPOT_RELEASE_VERSION)" != ""
-HOTSPOT_RELEASE_VERSION="\\\"$(HOTSPOT_RELEASE_VERSION)\\\""
-!else
-HOTSPOT_RELEASE_VERSION="\\\"$(HS_MAJOR_VER).$(HS_MINOR_VER)-b$(HS_BUILD_NUMBER)-$(HOTSPOT_BUILD_VERSION)\\\""
-!endif
!if "$(JRE_RELEASE_VERSION)" != ""
JRE_RELEASE_VERSION="\\\"$(JRE_RELEASE_VERSION)\\\""
!else
JRE_RELEASE_VERSION="\\\"$(JDK_MAJOR_VER).$(JDK_MINOR_VER).$(JDK_MICRO_VER)\\\""
!endif
-
+!if "$(HOTSPOT_RELEASE_VERSION)" != ""
+HOTSPOT_RELEASE_VERSION="\\\"$(HOTSPOT_RELEASE_VERSION)\\\""
+!else
+HOTSPOT_RELEASE_VERSION="\\\"$(JRE_RELEASE_VERSION)\\\""
+!endif
# Define HOTSPOT_VM_DISTRO if HOTSPOT_VM_DISTRO is set,
# and if it is not see if we have the src/closed directory
!if "$(HOTSPOT_VM_DISTRO)" != ""
--- a/hotspot/src/os/bsd/vm/os_bsd.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/os/bsd/vm/os_bsd.cpp Mon May 12 09:37:50 2014 -0700
@@ -127,8 +127,12 @@
// global variables
julong os::Bsd::_physical_memory = 0;
-
+#ifdef __APPLE__
+mach_timebase_info_data_t os::Bsd::_timebase_info = {0, 0};
+volatile uint64_t os::Bsd::_max_abstime = 0;
+#else
int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;
+#endif
pthread_t os::Bsd::_main_thread;
int os::Bsd::_page_size = -1;
@@ -986,13 +990,15 @@
return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000);
}
+#ifndef __APPLE__
#ifndef CLOCK_MONOTONIC
#define CLOCK_MONOTONIC (1)
#endif
+#endif
#ifdef __APPLE__
void os::Bsd::clock_init() {
- // XXXDARWIN: Investigate replacement monotonic clock
+ mach_timebase_info(&_timebase_info);
}
#else
void os::Bsd::clock_init() {
@@ -1007,10 +1013,39 @@
#endif
+
+#ifdef __APPLE__
+
+jlong os::javaTimeNanos() {
+ const uint64_t tm = mach_absolute_time();
+ const uint64_t now = (tm * Bsd::_timebase_info.numer) / Bsd::_timebase_info.denom;
+ const uint64_t prev = Bsd::_max_abstime;
+ if (now <= prev) {
+ return prev; // same or retrograde time;
+ }
+ const uint64_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&Bsd::_max_abstime, prev);
+ assert(obsv >= prev, "invariant"); // Monotonicity
+ // If the CAS succeeded then we're done and return "now".
+ // If the CAS failed and the observed value "obsv" is >= now then
+ // we should return "obsv". If the CAS failed and now > obsv > prv then
+ // some other thread raced this thread and installed a new value, in which case
+ // we could either (a) retry the entire operation, (b) retry trying to install now
+ // or (c) just return obsv. We use (c). No loop is required although in some cases
+ // we might discard a higher "now" value in deference to a slightly lower but freshly
+ // installed obsv value. That's entirely benign -- it admits no new orderings compared
+ // to (a) or (b) -- and greatly reduces coherence traffic.
+ // We might also condition (c) on the magnitude of the delta between obsv and now.
+ // Avoiding excessive CAS operations to hot RW locations is critical.
+ // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
+ return (prev == obsv) ? now : obsv;
+}
+
+#else // __APPLE__
+
jlong os::javaTimeNanos() {
if (os::supports_monotonic_clock()) {
struct timespec tp;
- int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp);
+ int status = Bsd::_clock_gettime(CLOCK_MONOTONIC, &tp);
assert(status == 0, "gettime error");
jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
return result;
@@ -1023,6 +1058,8 @@
}
}
+#endif // __APPLE__
+
void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
if (os::supports_monotonic_clock()) {
info_ptr->max_value = ALL_64_BITS;
--- a/hotspot/src/os/bsd/vm/os_bsd.hpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/os/bsd/vm/os_bsd.hpp Mon May 12 09:37:50 2014 -0700
@@ -58,7 +58,13 @@
// For signal flags diagnostics
static int sigflags[MAXSIGNUM];
+#ifdef __APPLE__
+ // mach_absolute_time
+ static mach_timebase_info_data_t _timebase_info;
+ static volatile uint64_t _max_abstime;
+#else
static int (*_clock_gettime)(clockid_t, struct timespec *);
+#endif
static GrowableArray<int>* _cpu_to_node;
@@ -134,10 +140,6 @@
// Real-time clock functions
static void clock_init(void);
- static int clock_gettime(clockid_t clock_id, struct timespec *tp) {
- return _clock_gettime ? _clock_gettime(clock_id, tp) : -1;
- }
-
// Stack repair handling
// none present
--- a/hotspot/src/os/bsd/vm/os_bsd.inline.hpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/os/bsd/vm/os_bsd.inline.hpp Mon May 12 09:37:50 2014 -0700
@@ -287,7 +287,11 @@
}
inline bool os::supports_monotonic_clock() {
+#ifdef __APPLE__
+ return true;
+#else
return Bsd::_clock_gettime != NULL;
+#endif
}
#endif // OS_BSD_VM_OS_BSD_INLINE_HPP
--- a/hotspot/src/os/solaris/vm/os_solaris.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/os/solaris/vm/os_solaris.cpp Mon May 12 09:37:50 2014 -0700
@@ -347,11 +347,7 @@
static hrtime_t first_hrtime = 0;
static const hrtime_t hrtime_hz = 1000*1000*1000;
-const int LOCK_BUSY = 1;
-const int LOCK_FREE = 0;
-const int LOCK_INVALID = -1;
static volatile hrtime_t max_hrtime = 0;
-static volatile int max_hrtime_lock = LOCK_FREE; // Update counter with LSB as lock-in-progress
void os::Solaris::initialize_system_info() {
@@ -1364,58 +1360,31 @@
}
-// gethrtime can move backwards if read from one cpu and then a different cpu
-// getTimeNanos is guaranteed to not move backward on Solaris
-// local spinloop created as faster for a CAS on an int than
-// a CAS on a 64bit jlong. Also Atomic::cmpxchg for jlong is not
-// supported on sparc v8 or pre supports_cx8 intel boxes.
-// oldgetTimeNanos for systems which do not support CAS on 64bit jlong
-// i.e. sparc v8 and pre supports_cx8 (i486) intel boxes
-inline hrtime_t oldgetTimeNanos() {
- int gotlock = LOCK_INVALID;
- hrtime_t newtime = gethrtime();
-
- for (;;) {
-// grab lock for max_hrtime
- int curlock = max_hrtime_lock;
- if (curlock & LOCK_BUSY) continue;
- if (gotlock = Atomic::cmpxchg(LOCK_BUSY, &max_hrtime_lock, LOCK_FREE) != LOCK_FREE) continue;
- if (newtime > max_hrtime) {
- max_hrtime = newtime;
- } else {
- newtime = max_hrtime;
- }
- // release lock
- max_hrtime_lock = LOCK_FREE;
- return newtime;
- }
-}
-// gethrtime can move backwards if read from one cpu and then a different cpu
-// getTimeNanos is guaranteed to not move backward on Solaris
+// gethrtime() should be monotonic according to the documentation,
+// but some virtualized platforms are known to break this guarantee.
+// getTimeNanos() must be guaranteed not to move backwards, so we
+// are forced to add a check here.
inline hrtime_t getTimeNanos() {
- if (VM_Version::supports_cx8()) {
- const hrtime_t now = gethrtime();
- // Use atomic long load since 32-bit x86 uses 2 registers to keep long.
- const hrtime_t prev = Atomic::load((volatile jlong*)&max_hrtime);
- if (now <= prev) return prev; // same or retrograde time;
- const hrtime_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&max_hrtime, prev);
- assert(obsv >= prev, "invariant"); // Monotonicity
- // If the CAS succeeded then we're done and return "now".
- // If the CAS failed and the observed value "obs" is >= now then
- // we should return "obs". If the CAS failed and now > obs > prv then
- // some other thread raced this thread and installed a new value, in which case
- // we could either (a) retry the entire operation, (b) retry trying to install now
- // or (c) just return obs. We use (c). No loop is required although in some cases
- // we might discard a higher "now" value in deference to a slightly lower but freshly
- // installed obs value. That's entirely benign -- it admits no new orderings compared
- // to (a) or (b) -- and greatly reduces coherence traffic.
- // We might also condition (c) on the magnitude of the delta between obs and now.
- // Avoiding excessive CAS operations to hot RW locations is critical.
- // See http://blogs.sun.com/dave/entry/cas_and_cache_trivia_invalidate
- return (prev == obsv) ? now : obsv ;
- } else {
- return oldgetTimeNanos();
- }
+ const hrtime_t now = gethrtime();
+ const hrtime_t prev = max_hrtime;
+ if (now <= prev) {
+ return prev; // same or retrograde time;
+ }
+ const hrtime_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&max_hrtime, prev);
+ assert(obsv >= prev, "invariant"); // Monotonicity
+ // If the CAS succeeded then we're done and return "now".
+ // If the CAS failed and the observed value "obsv" is >= now then
+ // we should return "obsv". If the CAS failed and now > obsv > prv then
+ // some other thread raced this thread and installed a new value, in which case
+ // we could either (a) retry the entire operation, (b) retry trying to install now
+ // or (c) just return obsv. We use (c). No loop is required although in some cases
+ // we might discard a higher "now" value in deference to a slightly lower but freshly
+ // installed obsv value. That's entirely benign -- it admits no new orderings compared
+ // to (a) or (b) -- and greatly reduces coherence traffic.
+ // We might also condition (c) on the magnitude of the delta between obsv and now.
+ // Avoiding excessive CAS operations to hot RW locations is critical.
+ // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
+ return (prev == obsv) ? now : obsv;
}
// Time since start-up in seconds to a fine granularity.
--- a/hotspot/src/os/windows/vm/os_windows.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/os/windows/vm/os_windows.cpp Mon May 12 09:37:50 2014 -0700
@@ -130,6 +130,13 @@
case DLL_PROCESS_DETACH:
if(ForceTimeHighResolution)
timeEndPeriod(1L);
+
+ // Workaround for issue when a custom launcher doesn't call
+ // DestroyJavaVM and NMT is trying to track memory when free is
+ // called from a static destructor
+ if (MemTracker::is_on()) {
+ MemTracker::shutdown(MemTracker::NMT_normal);
+ }
break;
default:
break;
--- a/hotspot/src/share/vm/classfile/javaClasses.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/classfile/javaClasses.cpp Mon May 12 09:37:50 2014 -0700
@@ -421,6 +421,15 @@
return UNICODE::as_utf8(position, len);
}
+char* java_lang_String::as_utf8_string(oop java_string, int start, int len, char* buf, int buflen) {
+ typeArrayOop value = java_lang_String::value(java_string);
+ int offset = java_lang_String::offset(java_string);
+ int length = java_lang_String::length(java_string);
+ assert(start + len <= length, "just checking");
+ jchar* position = value->char_at_addr(offset + start);
+ return UNICODE::as_utf8(position, len, buf, buflen);
+}
+
bool java_lang_String::equals(oop java_string, jchar* chars, int len) {
assert(java_string->klass() == SystemDictionary::String_klass(),
"must be java_string");
--- a/hotspot/src/share/vm/classfile/javaClasses.hpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/classfile/javaClasses.hpp Mon May 12 09:37:50 2014 -0700
@@ -162,6 +162,7 @@
static char* as_utf8_string(oop java_string);
static char* as_utf8_string(oop java_string, char* buf, int buflen);
static char* as_utf8_string(oop java_string, int start, int len);
+ static char* as_utf8_string(oop java_string, int start, int len, char* buf, int buflen);
static char* as_platform_dependent_str(Handle java_string, TRAPS);
static jchar* as_unicode_string(oop java_string, int& length, TRAPS);
// produce an ascii string with all other values quoted using \u####
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp Mon May 12 09:37:50 2014 -0700
@@ -1282,6 +1282,7 @@
Universe::verify(VerifyOption_G1UsePrevMarking,
" VerifyDuringGC:(before)");
}
+ g1h->check_bitmaps("Remark Start");
G1CollectorPolicy* g1p = g1h->g1_policy();
g1p->record_concurrent_mark_remark_start();
@@ -1330,6 +1331,7 @@
Universe::verify(VerifyOption_G1UseNextMarking,
" VerifyDuringGC:(after)");
}
+ g1h->check_bitmaps("Remark End");
assert(!restart_for_overflow(), "sanity");
// Completely reset the marking state since marking completed
set_non_marking_state();
@@ -1979,6 +1981,7 @@
Universe::verify(VerifyOption_G1UsePrevMarking,
" VerifyDuringGC:(before)");
}
+ g1h->check_bitmaps("Cleanup Start");
G1CollectorPolicy* g1p = G1CollectedHeap::heap()->g1_policy();
g1p->record_concurrent_mark_cleanup_start();
@@ -2133,6 +2136,7 @@
Universe::verify(VerifyOption_G1UsePrevMarking,
" VerifyDuringGC:(after)");
}
+ g1h->check_bitmaps("Cleanup End");
g1h->verify_region_sets_optional();
g1h->trace_heap_after_concurrent_cycle();
@@ -3224,6 +3228,11 @@
void ConcurrentMark::abort() {
// Clear all marks to force marking thread to do nothing
_nextMarkBitMap->clearAll();
+
+ // Note we cannot clear the previous marking bitmap here
+ // since VerifyDuringGC verifies the objects marked during
+ // a full GC against the previous bitmap.
+
// Clear the liveness counting data
clear_all_count_data();
// Empty mark stack
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp Mon May 12 09:37:50 2014 -0700
@@ -768,6 +768,7 @@
// match new_top.
assert(hr == NULL ||
(hr->end() == new_end && hr->top() == new_top), "sanity");
+ check_bitmaps("Humongous Region Allocation", first_hr);
assert(first_hr->used() == word_size * HeapWordSize, "invariant");
_summary_bytes_used += first_hr->used();
@@ -1326,6 +1327,7 @@
verify_before_gc();
+ check_bitmaps("Full GC Start");
pre_full_gc_dump(gc_timer);
COMPILER2_PRESENT(DerivedPointerTable::clear());
@@ -1499,6 +1501,18 @@
verify_after_gc();
+ // Clear the previous marking bitmap, if needed for bitmap verification.
+ // Note we cannot do this when we clear the next marking bitmap in
+ // ConcurrentMark::abort() above since VerifyDuringGC verifies the
+ // objects marked during a full GC against the previous bitmap.
+ // But we need to clear it before calling check_bitmaps below since
+ // the full GC has compacted objects and updated TAMS but not updated
+ // the prev bitmap.
+ if (G1VerifyBitmaps) {
+ ((CMBitMap*) concurrent_mark()->prevMarkBitMap())->clearAll();
+ }
+ check_bitmaps("Full GC End");
+
// Start a new incremental collection set for the next pause
assert(g1_policy()->collection_set() == NULL, "must be");
g1_policy()->start_incremental_cset_building();
@@ -3978,6 +3992,7 @@
increment_gc_time_stamp();
verify_before_gc();
+ check_bitmaps("GC Start");
COMPILER2_PRESENT(DerivedPointerTable::clear());
@@ -4223,6 +4238,7 @@
increment_gc_time_stamp();
verify_after_gc();
+ check_bitmaps("GC End");
assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
ref_processor_stw()->verify_no_references_recorded();
@@ -5945,6 +5961,11 @@
assert(!hr->is_empty(), "the region should not be empty");
assert(free_list != NULL, "pre-condition");
+ if (G1VerifyBitmaps) {
+ MemRegion mr(hr->bottom(), hr->end());
+ concurrent_mark()->clearRangePrevBitmap(mr);
+ }
+
// Clear the card counts for this region.
// Note: we only need to do this if the region is not young
// (since we don't refine cards in young regions).
@@ -6079,7 +6100,87 @@
void G1CollectedHeap::verify_dirty_young_regions() {
verify_dirty_young_list(_young_list->first_region());
}
-#endif
+
+bool G1CollectedHeap::verify_no_bits_over_tams(const char* bitmap_name, CMBitMapRO* bitmap,
+ HeapWord* tams, HeapWord* end) {
+ guarantee(tams <= end,
+ err_msg("tams: "PTR_FORMAT" end: "PTR_FORMAT, tams, end));
+ HeapWord* result = bitmap->getNextMarkedWordAddress(tams, end);
+ if (result < end) {
+ gclog_or_tty->cr();
+ gclog_or_tty->print_cr("## wrong marked address on %s bitmap: "PTR_FORMAT,
+ bitmap_name, result);
+ gclog_or_tty->print_cr("## %s tams: "PTR_FORMAT" end: "PTR_FORMAT,
+ bitmap_name, tams, end);
+ return false;
+ }
+ return true;
+}
+
+bool G1CollectedHeap::verify_bitmaps(const char* caller, HeapRegion* hr) {
+ CMBitMapRO* prev_bitmap = concurrent_mark()->prevMarkBitMap();
+ CMBitMapRO* next_bitmap = (CMBitMapRO*) concurrent_mark()->nextMarkBitMap();
+
+ HeapWord* bottom = hr->bottom();
+ HeapWord* ptams = hr->prev_top_at_mark_start();
+ HeapWord* ntams = hr->next_top_at_mark_start();
+ HeapWord* end = hr->end();
+
+ bool res_p = verify_no_bits_over_tams("prev", prev_bitmap, ptams, end);
+
+ bool res_n = true;
+ // We reset mark_in_progress() before we reset _cmThread->in_progress() and in this window
+ // we do the clearing of the next bitmap concurrently. Thus, we can not verify the bitmap
+ // if we happen to be in that state.
+ if (mark_in_progress() || !_cmThread->in_progress()) {
+ res_n = verify_no_bits_over_tams("next", next_bitmap, ntams, end);
+ }
+ if (!res_p || !res_n) {
+ gclog_or_tty->print_cr("#### Bitmap verification failed for "HR_FORMAT,
+ HR_FORMAT_PARAMS(hr));
+ gclog_or_tty->print_cr("#### Caller: %s", caller);
+ return false;
+ }
+ return true;
+}
+
+void G1CollectedHeap::check_bitmaps(const char* caller, HeapRegion* hr) {
+ if (!G1VerifyBitmaps) return;
+
+ guarantee(verify_bitmaps(caller, hr), "bitmap verification");
+}
+
+class G1VerifyBitmapClosure : public HeapRegionClosure {
+private:
+ const char* _caller;
+ G1CollectedHeap* _g1h;
+ bool _failures;
+
+public:
+ G1VerifyBitmapClosure(const char* caller, G1CollectedHeap* g1h) :
+ _caller(caller), _g1h(g1h), _failures(false) { }
+
+ bool failures() { return _failures; }
+
+ virtual bool doHeapRegion(HeapRegion* hr) {
+ if (hr->continuesHumongous()) return false;
+
+ bool result = _g1h->verify_bitmaps(_caller, hr);
+ if (!result) {
+ _failures = true;
+ }
+ return false;
+ }
+};
+
+void G1CollectedHeap::check_bitmaps(const char* caller) {
+ if (!G1VerifyBitmaps) return;
+
+ G1VerifyBitmapClosure cl(caller, this);
+ heap_region_iterate(&cl);
+ guarantee(!cl.failures(), "bitmap verification");
+}
+#endif // PRODUCT
void G1CollectedHeap::cleanUpCardTable() {
G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
@@ -6464,6 +6565,7 @@
if (new_alloc_region != NULL) {
set_region_short_lived_locked(new_alloc_region);
_hr_printer.alloc(new_alloc_region, G1HRPrinter::Eden, young_list_full);
+ check_bitmaps("Mutator Region Allocation", new_alloc_region);
return new_alloc_region;
}
}
@@ -6530,8 +6632,10 @@
if (survivor) {
new_alloc_region->set_survivor();
_hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor);
+ check_bitmaps("Survivor Region Allocation", new_alloc_region);
} else {
_hr_printer.alloc(new_alloc_region, G1HRPrinter::Old);
+ check_bitmaps("Old Region Allocation", new_alloc_region);
}
bool during_im = g1_policy()->during_initial_mark_pause();
new_alloc_region->note_start_of_copying(during_im);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp Mon May 12 09:37:50 2014 -0700
@@ -1186,6 +1186,30 @@
void verify_dirty_young_list(HeapRegion* head) PRODUCT_RETURN;
void verify_dirty_young_regions() PRODUCT_RETURN;
+#ifndef PRODUCT
+ // Make sure that the given bitmap has no marked objects in the
+ // range [from,limit). If it does, print an error message and return
+ // false. Otherwise, just return true. bitmap_name should be "prev"
+ // or "next".
+ bool verify_no_bits_over_tams(const char* bitmap_name, CMBitMapRO* bitmap,
+ HeapWord* from, HeapWord* limit);
+
+ // Verify that the prev / next bitmap range [tams,end) for the given
+ // region has no marks. Return true if all is well, false if errors
+ // are detected.
+ bool verify_bitmaps(const char* caller, HeapRegion* hr);
+#endif // PRODUCT
+
+ // If G1VerifyBitmaps is set, verify that the marking bitmaps for
+ // the given region do not have any spurious marks. If errors are
+ // detected, print appropriate error messages and crash.
+ void check_bitmaps(const char* caller, HeapRegion* hr) PRODUCT_RETURN;
+
+ // If G1VerifyBitmaps is set, verify that the marking bitmaps do not
+ // have any spurious marks. If errors are detected, print
+ // appropriate error messages and crash.
+ void check_bitmaps(const char* caller) PRODUCT_RETURN;
+
// verify_region_sets() performs verification over the region
// lists. It will be compiled in the product code to be used when
// necessary (i.e., during heap verification).
--- a/hotspot/src/share/vm/gc_implementation/g1/g1EvacFailure.hpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1EvacFailure.hpp Mon May 12 09:37:50 2014 -0700
@@ -191,6 +191,7 @@
hr->note_self_forwarding_removal_start(during_initial_mark,
during_conc_mark);
+ _g1h->check_bitmaps("Self-Forwarding Ptr Removal", hr);
// In the common case (i.e. when there is no evacuation
// failure) we make sure that the following is done when
--- a/hotspot/src/share/vm/gc_implementation/g1/g1_globals.hpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1_globals.hpp Mon May 12 09:37:50 2014 -0700
@@ -325,11 +325,14 @@
"evacuation pauses") \
\
diagnostic(bool, G1VerifyRSetsDuringFullGC, false, \
- "If true, perform verification of each heap region's " \
- "remembered set when verifying the heap during a full GC.") \
+ "If true, perform verification of each heap region's " \
+ "remembered set when verifying the heap during a full GC.") \
\
diagnostic(bool, G1VerifyHeapRegionCodeRoots, false, \
- "Verify the code root lists attached to each heap region.")
+ "Verify the code root lists attached to each heap region.") \
+ \
+ develop(bool, G1VerifyBitmaps, false, \
+ "Verifies the consistency of the marking bitmaps")
G1_FLAGS(DECLARE_DEVELOPER_FLAG, DECLARE_PD_DEVELOPER_FLAG, DECLARE_PRODUCT_FLAG, DECLARE_PD_PRODUCT_FLAG, DECLARE_DIAGNOSTIC_FLAG, DECLARE_EXPERIMENTAL_FLAG, DECLARE_NOTPRODUCT_FLAG, DECLARE_MANAGEABLE_FLAG, DECLARE_PRODUCT_RW_FLAG)
--- a/hotspot/src/share/vm/oops/klass.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/oops/klass.cpp Mon May 12 09:37:50 2014 -0700
@@ -488,6 +488,7 @@
}
void Klass::restore_unshareable_info(TRAPS) {
+ TRACE_INIT_ID(this);
// If an exception happened during CDS restore, some of these fields may already be
// set. We leave the class on the CLD list, even if incomplete so that we don't
// modify the CLD list outside a safepoint.
--- a/hotspot/src/share/vm/prims/jni.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/prims/jni.cpp Mon May 12 09:37:50 2014 -0700
@@ -3150,11 +3150,9 @@
} else {
//%note jni_7
if (len > 0) {
- ResourceMark rm(THREAD);
- char *utf_region = java_lang_String::as_utf8_string(s, start, len);
- int utf_len = (int)strlen(utf_region);
- memcpy(buf, utf_region, utf_len);
- buf[utf_len] = 0;
+ // Assume the buffer is large enough as the JNI spec. does not require user error checking
+ java_lang_String::as_utf8_string(s, start, len, buf, INT_MAX);
+ // as_utf8_string null-terminates the result string
} else {
// JDK null-terminates the buffer even in len is zero
if (buf != NULL) {
@@ -3880,6 +3878,7 @@
void TestOldSize_test();
void TestKlass_test();
void TestBitMap_test();
+void TestAsUtf8();
#if INCLUDE_ALL_GCS
void TestOldFreeSpaceCalculation_test();
void TestG1BiasedArray_test();
@@ -3907,6 +3906,7 @@
run_unit_test(TestOldSize_test());
run_unit_test(TestKlass_test());
run_unit_test(TestBitMap_test());
+ run_unit_test(TestAsUtf8());
#if INCLUDE_VM_STRUCTS
run_unit_test(VMStructs::test());
#endif
--- a/hotspot/src/share/vm/prims/jvm.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvm.cpp Mon May 12 09:37:50 2014 -0700
@@ -386,6 +386,23 @@
JVM_END
+/*
+ * Return the temporary directory that the VM uses for the attach
+ * and perf data files.
+ *
+ * It is important that this directory is well-known and the
+ * same for all VM instances. It cannot be affected by configuration
+ * variables such as java.io.tmpdir.
+ */
+JVM_ENTRY(jstring, JVM_GetTemporaryDirectory(JNIEnv *env))
+ JVMWrapper("JVM_GetTemporaryDirectory");
+ HandleMark hm(THREAD);
+ const char* temp_dir = os::get_temp_directory();
+ Handle h = java_lang_String::create_from_platform_dependent_str(temp_dir, CHECK_NULL);
+ return (jstring) JNIHandles::make_local(env, h());
+JVM_END
+
+
// java.lang.Runtime /////////////////////////////////////////////////////////////////////////
extern volatile jint vm_created;
--- a/hotspot/src/share/vm/prims/jvm.h Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvm.h Mon May 12 09:37:50 2014 -0700
@@ -1485,6 +1485,9 @@
JNIEXPORT jobject JNICALL
JVM_InitAgentProperties(JNIEnv *env, jobject agent_props);
+JNIEXPORT jstring JNICALL
+JVM_GetTemporaryDirectory(JNIEnv *env);
+
/* Generics reflection support.
*
* Returns information about the given class's EnclosingMethod
@@ -1553,12 +1556,10 @@
* ==========================================================================
*/
typedef struct {
- /* HotSpot Express VM version string:
- * <major>.<minor>-bxx[-<identifier>][-<debug_flavor>]
- */
- unsigned int jvm_version; /* Consists of major.minor.0.build */
- unsigned int update_version : 8; /* 0 in HotSpot Express VM */
- unsigned int special_update_version : 8; /* 0 in HotSpot Express VM */
+ /* VM version string: follows the JDK release version naming convention */
+ unsigned int jvm_version; /* <major_ver>.<minor_ver>.<micro_ver>[-<identifier>][-<debug_target>][-b<nn>] */
+ unsigned int update_version : 8;
+ unsigned int special_update_version : 8;
unsigned int reserved1 : 16;
unsigned int reserved2;
@@ -1577,11 +1578,7 @@
#define JVM_VERSION_MAJOR(version) ((version & 0xFF000000) >> 24)
#define JVM_VERSION_MINOR(version) ((version & 0x00FF0000) >> 16)
-// Micro version is 0 in HotSpot Express VM (set in jvm.cpp).
#define JVM_VERSION_MICRO(version) ((version & 0x0000FF00) >> 8)
-/* Build number is available in all HotSpot Express VM builds.
- * It is defined in make/hotspot_version file.
- */
#define JVM_VERSION_BUILD(version) ((version & 0x000000FF))
JNIEXPORT void JNICALL
--- a/hotspot/src/share/vm/runtime/os.hpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/runtime/os.hpp Mon May 12 09:37:50 2014 -0700
@@ -48,6 +48,9 @@
#ifdef TARGET_OS_FAMILY_bsd
# include "jvm_bsd.h"
# include <setjmp.h>
+# ifdef __APPLE__
+# include <mach/mach_time.h>
+# endif
#endif
class AgentLibrary;
--- a/hotspot/src/share/vm/runtime/vmStructs.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/runtime/vmStructs.cpp Mon May 12 09:37:50 2014 -0700
@@ -1218,6 +1218,7 @@
static_field(Abstract_VM_Version, _s_internal_vm_info_string, const char*) \
static_field(Abstract_VM_Version, _vm_major_version, int) \
static_field(Abstract_VM_Version, _vm_minor_version, int) \
+ static_field(Abstract_VM_Version, _vm_micro_version, int) \
static_field(Abstract_VM_Version, _vm_build_number, int) \
static_field(Abstract_VM_Version, _reserve_for_allocation_prefetch, int) \
\
--- a/hotspot/src/share/vm/runtime/vm_version.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/runtime/vm_version.cpp Mon May 12 09:37:50 2014 -0700
@@ -55,6 +55,20 @@
#ifndef HOTSPOT_RELEASE_VERSION
#error HOTSPOT_RELEASE_VERSION must be defined
#endif
+
+#ifndef JDK_MAJOR_VERSION
+ #error JDK_MAJOR_VERSION must be defined
+#endif
+#ifndef JDK_MINOR_VERSION
+ #error JDK_MINOR_VERSION must be defined
+#endif
+#ifndef JDK_MICRO_VERSION
+ #error JDK_MICRO_VERSION must be defined
+#endif
+#ifndef JDK_BUILD_NUMBER
+ #error JDK_BUILD_NUMBER must be defined
+#endif
+
#ifndef JRE_RELEASE_VERSION
#error JRE_RELEASE_VERSION must be defined
#endif
@@ -68,39 +82,44 @@
#define VM_RELEASE HOTSPOT_RELEASE_VERSION "-" HOTSPOT_BUILD_TARGET
#endif
-// HOTSPOT_RELEASE_VERSION must follow the release version naming convention
-// <major_ver>.<minor_ver>-b<nn>[-<identifier>][-<debug_target>]
+// HOTSPOT_RELEASE_VERSION follows the JDK release version naming convention
+// <major_ver>.<minor_ver>.<micro_ver>[-<identifier>][-<debug_target>][-b<nn>]
int Abstract_VM_Version::_vm_major_version = 0;
int Abstract_VM_Version::_vm_minor_version = 0;
+int Abstract_VM_Version::_vm_micro_version = 0;
int Abstract_VM_Version::_vm_build_number = 0;
bool Abstract_VM_Version::_initialized = false;
int Abstract_VM_Version::_parallel_worker_threads = 0;
bool Abstract_VM_Version::_parallel_worker_threads_initialized = false;
+#ifdef ASSERT
+static void assert_digits(const char * s, const char * message) {
+ for (int i = 0; s[i] != '\0'; i++) {
+ assert(isdigit(s[i]), message);
+ }
+}
+#endif
+
+static void set_version_field(int * version_field, const char * version_str,
+ const char * const assert_msg) {
+ if (version_str != NULL && *version_str != '\0') {
+ DEBUG_ONLY(assert_digits(version_str, assert_msg));
+ *version_field = atoi(version_str);
+ }
+}
+
void Abstract_VM_Version::initialize() {
if (_initialized) {
return;
}
- char* vm_version = os::strdup(HOTSPOT_RELEASE_VERSION);
- // Expecting the next vm_version format:
- // <major_ver>.<minor_ver>-b<nn>[-<identifier>]
- char* vm_major_ver = vm_version;
- assert(isdigit(vm_major_ver[0]),"wrong vm major version number");
- char* vm_minor_ver = strchr(vm_major_ver, '.');
- assert(vm_minor_ver != NULL && isdigit(vm_minor_ver[1]),"wrong vm minor version number");
- vm_minor_ver[0] = '\0'; // terminate vm_major_ver
- vm_minor_ver += 1;
- char* vm_build_num = strchr(vm_minor_ver, '-');
- assert(vm_build_num != NULL && vm_build_num[1] == 'b' && isdigit(vm_build_num[2]),"wrong vm build number");
- vm_build_num[0] = '\0'; // terminate vm_minor_ver
- vm_build_num += 2;
+ set_version_field(&_vm_major_version, JDK_MAJOR_VERSION, "bad major version");
+ set_version_field(&_vm_minor_version, JDK_MINOR_VERSION, "bad minor version");
+ set_version_field(&_vm_micro_version, JDK_MICRO_VERSION, "bad micro version");
+ int offset = (JDK_BUILD_NUMBER != NULL && JDK_BUILD_NUMBER[0] == 'b') ? 1 : 0;
+ set_version_field(&_vm_build_number, JDK_BUILD_NUMBER + offset,
+ "bad build number");
- _vm_major_version = atoi(vm_major_ver);
- _vm_minor_version = atoi(vm_minor_ver);
- _vm_build_number = atoi(vm_build_num);
-
- os::free(vm_version);
_initialized = true;
}
@@ -276,6 +295,7 @@
unsigned int Abstract_VM_Version::jvm_version() {
return ((Abstract_VM_Version::vm_major_version() & 0xFF) << 24) |
((Abstract_VM_Version::vm_minor_version() & 0xFF) << 16) |
+ ((Abstract_VM_Version::vm_micro_version() & 0xFF) << 8) |
(Abstract_VM_Version::vm_build_number() & 0xFF);
}
--- a/hotspot/src/share/vm/runtime/vm_version.hpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/runtime/vm_version.hpp Mon May 12 09:37:50 2014 -0700
@@ -44,6 +44,7 @@
static unsigned int _logical_processors_per_package;
static int _vm_major_version;
static int _vm_minor_version;
+ static int _vm_micro_version;
static int _vm_build_number;
static bool _initialized;
static int _parallel_worker_threads;
@@ -68,6 +69,7 @@
static int vm_major_version() { assert(_initialized, "not initialized"); return _vm_major_version; }
static int vm_minor_version() { assert(_initialized, "not initialized"); return _vm_minor_version; }
+ static int vm_micro_version() { assert(_initialized, "not initialized"); return _vm_micro_version; }
static int vm_build_number() { assert(_initialized, "not initialized"); return _vm_build_number; }
// Gets the jvm_version_info.jvm_version defined in jvm.h
--- a/hotspot/src/share/vm/services/memTracker.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/services/memTracker.cpp Mon May 12 09:37:50 2014 -0700
@@ -785,7 +785,7 @@
MEMFLAGS flags, address pc) {
assert(old_addr != NULL && new_addr != NULL, "Sanity check");
assert(_op == Realloc || _op == NoOp, "Wrong call");
- if (MemTracker::is_on() && NMT_CAN_TRACK(flags) && _op != NoOp) {
+ if (MemTracker::is_on() && NMT_CAN_TRACK(flags) && _op != NoOp && !MemTracker::shutdown_in_progress()) {
assert(_seq > 0, "Need pre-reserve sequence number");
if (_need_thread_critical_lock) {
ThreadCritical tc;
@@ -811,7 +811,7 @@
// OOM already?
if (addr == NULL) return;
- if (MemTracker::is_on() && NMT_CAN_TRACK(flags) && _op != NoOp) {
+ if (MemTracker::is_on() && NMT_CAN_TRACK(flags) && _op != NoOp && !MemTracker::shutdown_in_progress()) {
bool pre_reserved_seq = (_seq != 0);
address pc = CALLER_CALLER_PC;
MEMFLAGS orig_flags = flags;
--- a/hotspot/src/share/vm/utilities/utf8.cpp Mon May 05 12:48:07 2014 -0700
+++ b/hotspot/src/share/vm/utilities/utf8.cpp Mon May 12 09:37:50 2014 -0700
@@ -329,23 +329,19 @@
char* UNICODE::as_utf8(jchar* base, int length) {
int utf8_len = utf8_length(base, length);
- u_char* result = NEW_RESOURCE_ARRAY(u_char, utf8_len + 1);
- u_char* p = result;
- for (int index = 0; index < length; index++) {
- p = utf8_write(p, base[index]);
- }
- *p = '\0';
- assert(p == &result[utf8_len], "length prediction must be correct");
- return (char*) result;
+ u_char* buf = NEW_RESOURCE_ARRAY(u_char, utf8_len + 1);
+ char* result = as_utf8(base, length, (char*) buf, utf8_len + 1);
+ assert((int) strlen(result) == utf8_len, "length prediction must be correct");
+ return result;
}
char* UNICODE::as_utf8(jchar* base, int length, char* buf, int buflen) {
u_char* p = (u_char*)buf;
- u_char* end = (u_char*)buf + buflen;
for (int index = 0; index < length; index++) {
jchar c = base[index];
- if (p + utf8_size(c) >= end) break; // string is truncated
- p = utf8_write(p, base[index]);
+ buflen -= utf8_size(c);
+ if (buflen <= 0) break; // string is truncated
+ p = utf8_write(p, c);
}
*p = '\0';
return buf;
@@ -389,3 +385,29 @@
}
*p = '\0';
}
+
+#ifndef PRODUCT
+void TestAsUtf8() {
+ char res[60];
+ jchar str[20];
+
+ for (int i = 0; i < 20; i++) {
+ str[i] = 0x0800; // char that is 2B in UTF-16 but 3B in UTF-8
+ }
+ str[19] = (jchar)'\0';
+
+ // The resulting string in UTF-8 is 3*19 bytes long, but should be truncated
+ UNICODE::as_utf8(str, 19, res, 10);
+ assert(strlen(res) == 9, "string should be truncated here");
+
+ UNICODE::as_utf8(str, 19, res, 18);
+ assert(strlen(res) == 15, "string should be truncated here");
+
+ UNICODE::as_utf8(str, 19, res, 20);
+ assert(strlen(res) == 18, "string should be truncated here");
+
+ // Test with an "unbounded" buffer
+ UNICODE::as_utf8(str, 19, res, INT_MAX);
+ assert(strlen(res) == 3*19, "string should end here");
+}
+#endif
--- a/jaxp/.hgtags Mon May 05 12:48:07 2014 -0700
+++ b/jaxp/.hgtags Mon May 12 09:37:50 2014 -0700
@@ -254,3 +254,4 @@
f93a792fe37279d4d37aea86a99f3abbdc6fe79b jdk9-b09
4ce98701efe3b28f6ce3ab23385445731e968af7 jdk9-b10
6b4280dceb00642f54d5bc1c2cb7d34c99a04992 jdk9-b11
+e88cecf5a21b760ff7d7761c2db6bb8c82bc9f0c jdk9-b12
--- a/jaxws/.hgtags Mon May 05 12:48:07 2014 -0700
+++ b/jaxws/.hgtags Mon May 12 09:37:50 2014 -0700
@@ -257,3 +257,4 @@
c9e8bb8c1144a966ca7b481142c6b5e55d14a29c jdk9-b09
9af43f4d215f6f19b1767f6ac66da931b8ee9535 jdk9-b10
1f953ba7db2b535e19f0354abfee6d67605e0684 jdk9-b11
+779f8b21c75f83e3918dac8499e4d0ecb3a54ed7 jdk9-b12
--- a/jdk/.hgtags Mon May 05 12:48:07 2014 -0700
+++ b/jdk/.hgtags Mon May 12 09:37:50 2014 -0700
@@ -254,3 +254,4 @@
2cef452ba711b17950da275fd15931925799f07c jdk9-b09
ab06ba2894313a47e4969ca37792ff119c49e711 jdk9-b10
47feccd164b7187a0147693a922ee47c6629643c jdk9-b11
+83d9bc20973de232cae45b139fdff8a4549c130f jdk9-b12
--- a/jdk/make/CompileJavaClasses.gmk Mon May 05 12:48:07 2014 -0700
+++ b/jdk/make/CompileJavaClasses.gmk Mon May 12 09:37:50 2014 -0700
@@ -84,8 +84,6 @@
SolarisUserDefinedFileAttributeView.java \
SolarisWatchService.java \
SolarisAclFileAttributeView.java \
- SolarisLoginModule.java \
- SolarisSystem.java \
sun/nio/ch/DevPollArrayWrapper.java \
sun/nio/ch/DevPollSelectorImpl.java \
sun/nio/ch/DevPollSelectorProvider.java \
@@ -100,15 +98,6 @@
EXCLUDES += com/oracle/security
endif
-ifneq ($(OPENJDK_TARGET_OS), windows)
- # Exclude Window security related files in src/share/classes
- EXFILES += NTLoginModule.java \
- NTSystem.java
-else
- EXFILES += UnixLoginModule.java \
- UnixSystem.java
-endif
-
ifeq ($(OPENJDK_TARGET_OS), windows)
# Don't build GTK L&F on Windows
EXCLUDES += com/sun/java/swing/plaf/gtk
--- a/jdk/make/mapfiles/libjava/mapfile-vers Mon May 05 12:48:07 2014 -0700
+++ b/jdk/make/mapfiles/libjava/mapfile-vers Mon May 12 09:37:50 2014 -0700
@@ -273,7 +273,8 @@
Java_sun_misc_VM_isSetUID;
Java_sun_misc_VM_initialize;
Java_sun_misc_VMSupport_initAgentProperties;
-
+ Java_sun_misc_VMSupport_getVMTemporaryDirectory;
+
# ZipFile.c needs this one
throwFileNotFoundException;
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java Mon May 12 09:37:50 2014 -0700
@@ -87,6 +87,10 @@
new Algorithm("", "SHA1withDSA", "Signature")
);
algorithmsMap.put(
+ XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256,
+ new Algorithm("", "SHA256withDSA", "Signature")
+ );
+ algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5,
new Algorithm("", "MD5withRSA", "Signature")
);
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java Mon May 12 09:37:50 2014 -0700
@@ -380,7 +380,12 @@
* This method registers the default algorithms.
*/
public static void registerDefaultAlgorithms() {
- algorithmHash.put(SignatureDSA.URI, SignatureDSA.class);
+ algorithmHash.put(
+ XMLSignature.ALGO_ID_SIGNATURE_DSA, SignatureDSA.class
+ );
+ algorithmHash.put(
+ XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256, SignatureDSA.SHA256.class
+ );
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, SignatureBaseRSA.SignatureRSASHA1.class
);
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java Mon May 12 09:37:50 2014 -0700
@@ -31,13 +31,15 @@
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
+import java.security.interfaces.DSAKey;
import java.security.spec.AlgorithmParameterSpec;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi;
+import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
-import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
public class SignatureDSA extends SignatureAlgorithmSpi {
@@ -45,19 +47,19 @@
private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(SignatureDSA.class.getName());
- /** Field URI */
- public static final String URI = Constants.SignatureSpecNS + "dsa-sha1";
-
/** Field algorithm */
private java.security.Signature signatureAlgorithm = null;
+ /** size of Q */
+ private int size;
+
/**
* Method engineGetURI
*
* @inheritDoc
*/
protected String engineGetURI() {
- return SignatureDSA.URI;
+ return XMLSignature.ALGO_ID_SIGNATURE_DSA;
}
/**
@@ -66,7 +68,7 @@
* @throws XMLSignatureException
*/
public SignatureDSA() throws XMLSignatureException {
- String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA.URI);
+ String algorithmID = JCEMapper.translateURItoJCEID(engineGetURI());
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID);
}
@@ -110,7 +112,8 @@
log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature));
}
- byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(signature);
+ byte[] jcebytes = JavaUtils.convertDsaXMLDSIGtoASN1(signature,
+ size/8);
return this.signatureAlgorithm.verify(jcebytes);
} catch (SignatureException ex) {
@@ -150,6 +153,7 @@
}
throw new XMLSignatureException("empty", ex);
}
+ size = ((DSAKey)publicKey).getParams().getQ().bitLength();
}
/**
@@ -159,7 +163,7 @@
try {
byte jcebytes[] = this.signatureAlgorithm.sign();
- return SignatureDSA.convertASN1toXMLDSIG(jcebytes);
+ return JavaUtils.convertDsaASN1toXMLDSIG(jcebytes, size/8);
} catch (IOException ex) {
throw new XMLSignatureException("empty", ex);
} catch (SignatureException ex) {
@@ -185,6 +189,7 @@
} catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex);
}
+ size = ((DSAKey)privateKey).getParams().getQ().bitLength();
}
/**
@@ -204,6 +209,7 @@
} catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex);
}
+ size = ((DSAKey)privateKey).getParams().getQ().bitLength();
}
/**
@@ -258,100 +264,6 @@
}
/**
- * Converts an ASN.1 DSA value to a XML Signature DSA Value.
- *
- * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
- * pairs; the XML Signature requires the core BigInteger values.
- *
- * @param asn1Bytes
- * @return the decode bytes
- *
- * @throws IOException
- * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
- */
- private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException {
-
- byte rLength = asn1Bytes[3];
- int i;
-
- for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--);
-
- byte sLength = asn1Bytes[5 + rLength];
- int j;
-
- for (j = sLength;
- (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--);
-
- if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2)
- || (asn1Bytes[2] != 2) || (i > 20)
- || (asn1Bytes[4 + rLength] != 2) || (j > 20)) {
- throw new IOException("Invalid ASN.1 format of DSA signature");
- }
- byte xmldsigBytes[] = new byte[40];
-
- System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i, i);
- System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes,
- 40 - j, j);
-
- return xmldsigBytes;
- }
-
- /**
- * Converts a XML Signature DSA Value to an ASN.1 DSA value.
- *
- * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
- * pairs; the XML Signature requires the core BigInteger values.
- *
- * @param xmldsigBytes
- * @return the encoded ASN.1 bytes
- *
- * @throws IOException
- * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
- */
- private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException {
-
- if (xmldsigBytes.length != 40) {
- throw new IOException("Invalid XMLDSIG format of DSA signature");
- }
-
- int i;
-
- for (i = 20; (i > 0) && (xmldsigBytes[20 - i] == 0); i--);
-
- int j = i;
-
- if (xmldsigBytes[20 - i] < 0) {
- j += 1;
- }
-
- int k;
-
- for (k = 20; (k > 0) && (xmldsigBytes[40 - k] == 0); k--);
-
- int l = k;
-
- if (xmldsigBytes[40 - k] < 0) {
- l += 1;
- }
-
- byte asn1Bytes[] = new byte[6 + j + l];
-
- asn1Bytes[0] = 48;
- asn1Bytes[1] = (byte) (4 + j + l);
- asn1Bytes[2] = 2;
- asn1Bytes[3] = (byte) j;
-
- System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i);
-
- asn1Bytes[4 + j] = 2;
- asn1Bytes[5 + j] = (byte) l;
-
- System.arraycopy(xmldsigBytes, 40 - k, asn1Bytes, (6 + j + l) - k, k);
-
- return asn1Bytes;
- }
-
- /**
* Method engineSetHMACOutputLength
*
* @param HMACOutputLength
@@ -373,4 +285,15 @@
) throws XMLSignatureException {
throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnDSA");
}
+
+ public static class SHA256 extends SignatureDSA {
+
+ public SHA256() throws XMLSignatureException {
+ super();
+ }
+
+ public String engineGetURI() {
+ return XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256;
+ }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java Mon May 12 09:37:50 2014 -0700
@@ -85,6 +85,10 @@
public static final String ALGO_ID_SIGNATURE_DSA =
Constants.SignatureSpecNS + "dsa-sha1";
+ /** Signature - Optional DSAwithSHA256 */
+ public static final String ALGO_ID_SIGNATURE_DSA_SHA256 =
+ Constants.SignatureSpec11NS + "dsa-sha256";
+
/** Signature - Recommended RSAwithSHA1 */
public static final String ALGO_ID_SIGNATURE_RSA =
Constants.SignatureSpecNS + "rsa-sha1";
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java Mon May 12 09:37:50 2014 -0700
@@ -145,4 +145,98 @@
return retBytes;
}
+
+ /**
+ * Converts an ASN.1 DSA value to a XML Signature DSA Value.
+ *
+ * The JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
+ * pairs (see section 2.2.2 of RFC 3279); the XML Signature requires the
+ * core BigInteger values.
+ *
+ * @param asn1Bytes the ASN.1 encoded bytes
+ * @param size size of r and s in bytes
+ * @return the XML Signature encoded bytes
+ * @throws IOException if the bytes are not encoded correctly
+ * @see <A HREF="http://www.w3.org/TR/xmldsig-core1/#sec-DSA">6.4.1 DSA</A>
+ */
+ public static byte[] convertDsaASN1toXMLDSIG(byte[] asn1Bytes, int size)
+ throws IOException
+ {
+ if (asn1Bytes[0] != 48 || asn1Bytes[1] != asn1Bytes.length - 2
+ || asn1Bytes[2] != 2) {
+ throw new IOException("Invalid ASN.1 format of DSA signature");
+ }
+
+ byte rLength = asn1Bytes[3];
+ int i;
+ for (i = rLength; i > 0 && asn1Bytes[4 + rLength - i] == 0; i--);
+
+ byte sLength = asn1Bytes[5 + rLength];
+ int j;
+ for (j = sLength;
+ j > 0 && asn1Bytes[6 + rLength + sLength - j] == 0; j--);
+
+ if (i > size || asn1Bytes[4 + rLength] != 2 || j > size) {
+ throw new IOException("Invalid ASN.1 format of DSA signature");
+ } else {
+ byte[] xmldsigBytes = new byte[size * 2];
+ System.arraycopy(asn1Bytes, 4 + rLength - i, xmldsigBytes,
+ size - i, i);
+ System.arraycopy(asn1Bytes, 6 + rLength + sLength - j,
+ xmldsigBytes, size * 2 - j, j);
+ return xmldsigBytes;
+ }
+ }
+
+ /**
+ * Converts an XML Signature DSA Value to a ASN.1 DSA value.
+ *
+ * The JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
+ * pairs (see section 2.2.2 of RFC 3279); the XML Signature requires the
+ * core BigInteger values.
+ *
+ * @param xmldsigBytes the XML Signature encoded bytes
+ * @param size size of r and s in bytes
+ * @return the ASN.1 encoded bytes
+ * @throws IOException if the bytes are not encoded correctly
+ * @see <A HREF="http://www.w3.org/TR/xmldsig-core1/#sec-DSA">6.4.1 DSA</A>
+ */
+ public static byte[] convertDsaXMLDSIGtoASN1(byte[] xmldsigBytes, int size)
+ throws IOException
+ {
+ int totalSize = size * 2;
+ if (xmldsigBytes.length != totalSize) {
+ throw new IOException("Invalid XMLDSIG format of DSA signature");
+ }
+
+ int i;
+ for (i = size; i > 0 && xmldsigBytes[size - i] == 0; i--);
+
+ int j = i;
+ if (xmldsigBytes[size - i] < 0) {
+ j++;
+ }
+
+ int k;
+ for (k = size; k > 0 && xmldsigBytes[totalSize - k] == 0; k--);
+
+ int l = k;
+ if (xmldsigBytes[totalSize - k] < 0) {
+ l++;
+ }
+
+ byte[] asn1Bytes = new byte[6 + j + l];
+ asn1Bytes[0] = 48;
+ asn1Bytes[1] = (byte)(4 + j + l);
+ asn1Bytes[2] = 2;
+ asn1Bytes[3] = (byte)j;
+ System.arraycopy(xmldsigBytes, size - i, asn1Bytes, 4 + j - i, i);
+
+ asn1Bytes[4 + j] = 2;
+ asn1Bytes[5 + j] = (byte) l;
+ System.arraycopy(xmldsigBytes, totalSize - k, asn1Bytes,
+ 6 + j + l - k, k);
+
+ return asn1Bytes;
+ }
}
--- a/jdk/src/share/classes/com/sun/security/auth/module/NTLoginModule.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/com/sun/security/auth/module/NTLoginModule.java Mon May 12 09:37:50 2014 -0700
@@ -139,15 +139,17 @@
succeeded = false; // Indicate not yet successful
- ntSystem = new NTSystem(debugNative);
- if (ntSystem == null) {
+ try {
+ ntSystem = new NTSystem(debugNative);
+ } catch (UnsatisfiedLinkError ule) {
if (debug) {
System.out.println("\t\t[NTLoginModule] " +
"Failed in NT login");
}
throw new FailedLoginException
("Failed in attempt to import the " +
- "underlying NT system identity information");
+ "underlying NT system identity information" +
+ " on " + System.getProperty("os.name"));
}
if (ntSystem.getName() == null) {
--- a/jdk/src/share/classes/com/sun/security/auth/module/SolarisLoginModule.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/com/sun/security/auth/module/SolarisLoginModule.java Mon May 12 09:37:50 2014 -0700
@@ -129,39 +129,39 @@
long[] solarisGroups = null;
- ss = new SolarisSystem();
-
- if (ss == null) {
+ try {
+ ss = new SolarisSystem();
+ } catch (UnsatisfiedLinkError ule) {
succeeded = false;
throw new FailedLoginException
("Failed in attempt to import " +
- "the underlying system identity information");
- } else {
- userPrincipal = new SolarisPrincipal(ss.getUsername());
- UIDPrincipal = new SolarisNumericUserPrincipal(ss.getUid());
- GIDPrincipal = new SolarisNumericGroupPrincipal(ss.getGid(), true);
- if (ss.getGroups() != null && ss.getGroups().length > 0)
- solarisGroups = ss.getGroups();
- for (int i = 0; i < solarisGroups.length; i++) {
- SolarisNumericGroupPrincipal ngp =
- new SolarisNumericGroupPrincipal
- (solarisGroups[i], false);
- if (!ngp.getName().equals(GIDPrincipal.getName()))
- supplementaryGroups.add(ngp);
- }
- if (debug) {
- System.out.println("\t\t[SolarisLoginModule]: " +
- "succeeded importing info: ");
- System.out.println("\t\t\tuid = " + ss.getUid());
- System.out.println("\t\t\tgid = " + ss.getGid());
- solarisGroups = ss.getGroups();
- for (int i = 0; i < solarisGroups.length; i++) {
- System.out.println("\t\t\tsupp gid = " + solarisGroups[i]);
- }
+ "the underlying system identity information" +
+ " on " + System.getProperty("os.name"));
+ }
+ userPrincipal = new SolarisPrincipal(ss.getUsername());
+ UIDPrincipal = new SolarisNumericUserPrincipal(ss.getUid());
+ GIDPrincipal = new SolarisNumericGroupPrincipal(ss.getGid(), true);
+ if (ss.getGroups() != null && ss.getGroups().length > 0)
+ solarisGroups = ss.getGroups();
+ for (int i = 0; i < solarisGroups.length; i++) {
+ SolarisNumericGroupPrincipal ngp =
+ new SolarisNumericGroupPrincipal
+ (solarisGroups[i], false);
+ if (!ngp.getName().equals(GIDPrincipal.getName()))
+ supplementaryGroups.add(ngp);
}
- succeeded = true;
- return true;
+ if (debug) {
+ System.out.println("\t\t[SolarisLoginModule]: " +
+ "succeeded importing info: ");
+ System.out.println("\t\t\tuid = " + ss.getUid());
+ System.out.println("\t\t\tgid = " + ss.getGid());
+ solarisGroups = ss.getGroups();
+ for (int i = 0; i < solarisGroups.length; i++) {
+ System.out.println("\t\t\tsupp gid = " + solarisGroups[i]);
+ }
}
+ succeeded = true;
+ return true;
}
/**
--- a/jdk/src/share/classes/com/sun/security/auth/module/SolarisSystem.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/com/sun/security/auth/module/SolarisSystem.java Mon May 12 09:37:50 2014 -0700
@@ -29,8 +29,10 @@
* <p> This class implementation retrieves and makes available Solaris
* UID/GID/groups information for the current user.
*
+ * @deprecated replaced by {@link UnixSystem}.
*/
-@jdk.Exported
+@jdk.Exported(false)
+@Deprecated
public class SolarisSystem {
private native void getSolarisInfo();
--- a/jdk/src/share/classes/com/sun/security/auth/module/UnixLoginModule.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/com/sun/security/auth/module/UnixLoginModule.java Mon May 12 09:37:50 2014 -0700
@@ -122,40 +122,40 @@
long[] unixGroups = null;
- ss = new UnixSystem();
-
- if (ss == null) {
+ try {
+ ss = new UnixSystem();
+ } catch (UnsatisfiedLinkError ule) {
succeeded = false;
throw new FailedLoginException
("Failed in attempt to import " +
- "the underlying system identity information");
- } else {
- userPrincipal = new UnixPrincipal(ss.getUsername());
- UIDPrincipal = new UnixNumericUserPrincipal(ss.getUid());
- GIDPrincipal = new UnixNumericGroupPrincipal(ss.getGid(), true);
- if (ss.getGroups() != null && ss.getGroups().length > 0) {
- unixGroups = ss.getGroups();
- for (int i = 0; i < unixGroups.length; i++) {
- UnixNumericGroupPrincipal ngp =
- new UnixNumericGroupPrincipal
- (unixGroups[i], false);
- if (!ngp.getName().equals(GIDPrincipal.getName()))
- supplementaryGroups.add(ngp);
- }
+ "the underlying system identity information" +
+ " on " + System.getProperty("os.name"));
+ }
+ userPrincipal = new UnixPrincipal(ss.getUsername());
+ UIDPrincipal = new UnixNumericUserPrincipal(ss.getUid());
+ GIDPrincipal = new UnixNumericGroupPrincipal(ss.getGid(), true);
+ if (ss.getGroups() != null && ss.getGroups().length > 0) {
+ unixGroups = ss.getGroups();
+ for (int i = 0; i < unixGroups.length; i++) {
+ UnixNumericGroupPrincipal ngp =
+ new UnixNumericGroupPrincipal
+ (unixGroups[i], false);
+ if (!ngp.getName().equals(GIDPrincipal.getName()))
+ supplementaryGroups.add(ngp);
}
- if (debug) {
- System.out.println("\t\t[UnixLoginModule]: " +
- "succeeded importing info: ");
- System.out.println("\t\t\tuid = " + ss.getUid());
- System.out.println("\t\t\tgid = " + ss.getGid());
- unixGroups = ss.getGroups();
- for (int i = 0; i < unixGroups.length; i++) {
- System.out.println("\t\t\tsupp gid = " + unixGroups[i]);
- }
+ }
+ if (debug) {
+ System.out.println("\t\t[UnixLoginModule]: " +
+ "succeeded importing info: ");
+ System.out.println("\t\t\tuid = " + ss.getUid());
+ System.out.println("\t\t\tgid = " + ss.getGid());
+ unixGroups = ss.getGroups();
+ for (int i = 0; i < unixGroups.length; i++) {
+ System.out.println("\t\t\tsupp gid = " + unixGroups[i]);
}
- succeeded = true;
- return true;
}
+ succeeded = true;
+ return true;
}
/**
--- a/jdk/src/share/classes/java/lang/Math.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/lang/Math.java Mon May 12 09:37:50 2014 -0700
@@ -1904,51 +1904,36 @@
* are naturally handled without any additional testing
*/
- // First check for NaN values
- if (Double.isNaN(start) || Double.isNaN(direction)) {
- // return a NaN derived from the input NaN(s)
- return start + direction;
- } else if (start == direction) {
- return direction;
- } else { // start > direction or start < direction
+ /*
+ * IEEE 754 floating-point numbers are lexicographically
+ * ordered if treated as signed-magnitude integers.
+ * Since Java's integers are two's complement,
+ * incrementing the two's complement representation of a
+ * logically negative floating-point value *decrements*
+ * the signed-magnitude representation. Therefore, when
+ * the integer representation of a floating-point value
+ * is negative, the adjustment to the representation is in
+ * the opposite direction from what would initially be expected.
+ */
+
+ // Branch to descending case first as it is more costly than ascending
+ // case due to start != 0.0d conditional.
+ if (start > direction) { // descending
+ if (start != 0.0d) {
+ final long transducer = Double.doubleToRawLongBits(start);
+ return Double.longBitsToDouble(transducer + ((transducer > 0L) ? -1L : 1L));
+ } else { // start == 0.0d && direction < 0.0d
+ return -Double.MIN_VALUE;
+ }
+ } else if (start < direction) { // ascending
// Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0)
// then bitwise convert start to integer.
- long transducer = Double.doubleToRawLongBits(start + 0.0d);
-
- /*
- * IEEE 754 floating-point numbers are lexicographically
- * ordered if treated as signed- magnitude integers .
- * Since Java's integers are two's complement,
- * incrementing" the two's complement representation of a
- * logically negative floating-point value *decrements*
- * the signed-magnitude representation. Therefore, when
- * the integer representation of a floating-point values
- * is less than zero, the adjustment to the representation
- * is in the opposite direction than would be expected at
- * first .
- */
- if (direction > start) { // Calculate next greater value
- transducer = transducer + (transducer >= 0L ? 1L:-1L);
- } else { // Calculate next lesser value
- assert direction < start;
- if (transducer > 0L)
- --transducer;
- else
- if (transducer < 0L )
- ++transducer;
- /*
- * transducer==0, the result is -MIN_VALUE
- *
- * The transition from zero (implicitly
- * positive) to the smallest negative
- * signed magnitude value must be done
- * explicitly.
- */
- else
- transducer = DoubleConsts.SIGN_BIT_MASK | 1L;
- }
-
- return Double.longBitsToDouble(transducer);
+ final long transducer = Double.doubleToRawLongBits(start + 0.0d);
+ return Double.longBitsToDouble(transducer + ((transducer >= 0L) ? 1L : -1L));
+ } else if (start == direction) {
+ return direction;
+ } else { // isNaN(start) || isNaN(direction)
+ return start + direction;
}
}
@@ -2003,51 +1988,36 @@
* are naturally handled without any additional testing
*/
- // First check for NaN values
- if (Float.isNaN(start) || Double.isNaN(direction)) {
- // return a NaN derived from the input NaN(s)
- return start + (float)direction;
- } else if (start == direction) {
- return (float)direction;
- } else { // start > direction or start < direction
+ /*
+ * IEEE 754 floating-point numbers are lexicographically
+ * ordered if treated as signed-magnitude integers.
+ * Since Java's integers are two's complement,
+ * incrementing the two's complement representation of a
+ * logically negative floating-point value *decrements*
+ * the signed-magnitude representation. Therefore, when
+ * the integer representation of a floating-point value
+ * is negative, the adjustment to the representation is in
+ * the opposite direction from what would initially be expected.
+ */
+
+ // Branch to descending case first as it is more costly than ascending
+ // case due to start != 0.0f conditional.
+ if (start > direction) { // descending
+ if (start != 0.0f) {
+ final int transducer = Float.floatToRawIntBits(start);
+ return Float.intBitsToFloat(transducer + ((transducer > 0) ? -1 : 1));
+ } else { // start == 0.0f && direction < 0.0f
+ return -Float.MIN_VALUE;
+ }
+ } else if (start < direction) { // ascending
// Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0)
// then bitwise convert start to integer.
- int transducer = Float.floatToRawIntBits(start + 0.0f);
-
- /*
- * IEEE 754 floating-point numbers are lexicographically
- * ordered if treated as signed- magnitude integers .
- * Since Java's integers are two's complement,
- * incrementing" the two's complement representation of a
- * logically negative floating-point value *decrements*
- * the signed-magnitude representation. Therefore, when
- * the integer representation of a floating-point values
- * is less than zero, the adjustment to the representation
- * is in the opposite direction than would be expected at
- * first.
- */
- if (direction > start) {// Calculate next greater value
- transducer = transducer + (transducer >= 0 ? 1:-1);
- } else { // Calculate next lesser value
- assert direction < start;
- if (transducer > 0)
- --transducer;
- else
- if (transducer < 0 )
- ++transducer;
- /*
- * transducer==0, the result is -MIN_VALUE
- *
- * The transition from zero (implicitly
- * positive) to the smallest negative
- * signed magnitude value must be done
- * explicitly.
- */
- else
- transducer = FloatConsts.SIGN_BIT_MASK | 1;
- }
-
- return Float.intBitsToFloat(transducer);
+ final int transducer = Float.floatToRawIntBits(start + 0.0f);
+ return Float.intBitsToFloat(transducer + ((transducer >= 0) ? 1 : -1));
+ } else if (start == direction) {
+ return (float)direction;
+ } else { // isNaN(start) || isNaN(direction)
+ return start + (float)direction;
}
}
@@ -2077,12 +2047,13 @@
* @since 1.6
*/
public static double nextUp(double d) {
- if( Double.isNaN(d) || d == Double.POSITIVE_INFINITY)
+ // Use a single conditional and handle the likely cases first.
+ if (d < Double.POSITIVE_INFINITY) {
+ // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0).
+ final long transducer = Double.doubleToRawLongBits(d + 0.0D);
+ return Double.longBitsToDouble(transducer + ((transducer >= 0L) ? 1L : -1L));
+ } else { // d is NaN or +Infinity
return d;
- else {
- d += 0.0d;
- return Double.longBitsToDouble(Double.doubleToRawLongBits(d) +
- ((d >= 0.0d)?+1L:-1L));
}
}
@@ -2112,12 +2083,13 @@
* @since 1.6
*/
public static float nextUp(float f) {
- if( Float.isNaN(f) || f == FloatConsts.POSITIVE_INFINITY)
+ // Use a single conditional and handle the likely cases first.
+ if (f < Float.POSITIVE_INFINITY) {
+ // Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0).
+ final int transducer = Float.floatToRawIntBits(f + 0.0F);
+ return Float.intBitsToFloat(transducer + ((transducer >= 0) ? 1 : -1));
+ } else { // f is NaN or +Infinity
return f;
- else {
- f += 0.0f;
- return Float.intBitsToFloat(Float.floatToRawIntBits(f) +
- ((f >= 0.0f)?+1:-1));
}
}
--- a/jdk/src/share/classes/java/net/ContentHandler.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/net/ContentHandler.java Mon May 12 09:37:50 2014 -0700
@@ -46,15 +46,28 @@
* <p>
* If no content handler could be found, URLConnection will
* look for a content handler in a user-defineable set of places.
- * By default it looks in sun.net.www.content, but users can define a
- * vertical-bar delimited set of class prefixes to search through in
- * addition by defining the java.content.handler.pkgs property.
- * The class name must be of the form:
- * <pre>
- * {package-prefix}.{major}.{minor}
- * e.g.
+ * Users can define a vertical-bar delimited set of class prefixes
+ * to search through by defining the <i>java.content.handler.pkgs</i>
+ * property. The class name must be of the form:
+ * <blockquote>
+ * <i>{package-prefix}.{major}.{minor}</i>
+ * <P>
+ * where <i>{major}.{minor}</i> is formed by taking the
+ * content-type string, replacing all slash characters with a
+ * {@code period} ('.'), and all other non-alphanumeric characters
+ * with the underscore character '{@code _}'. The alphanumeric
+ * characters are specifically the 26 uppercase ASCII letters
+ * '{@code A}' through '{@code Z}', the 26 lowercase ASCII
+ * letters '{@code a}' through '{@code z}', and the 10 ASCII
+ * digits '{@code 0}' through '{@code 9}'.
+ * <p>
+ * e.g.
* YoyoDyne.experimental.text.plain
- * </pre>
+ * </blockquote>
+ * If no user-defined content handler is found, then the system
+ * tries to load a specific <i>content-type</i> handler from one
+ * of the built-in handlers, if one exists.
+ * <p>
* If the loading of the content handler class would be performed by
* a classloader that is outside of the delegation chain of the caller,
* the JVM will need the RuntimePermission "getClassLoader".
--- a/jdk/src/share/classes/java/net/URL.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/net/URL.java Mon May 12 09:37:50 2014 -0700
@@ -266,10 +266,7 @@
* a subclass of {@code URLStreamHandler}, then the next package
* in the list is tried.
* <li>If the previous step fails to find a protocol handler, then the
- * constructor tries to load from a system default package.
- * <blockquote><pre>
- * <<i>system default package</i>>.<<i>protocol</i>>.Handler
- * </pre></blockquote>
+ * constructor tries to load a built-in protocol handler.
* If this class does not exist, or if the class exists but it is not a
* subclass of {@code URLStreamHandler}, then a
* {@code MalformedURLException} is thrown.
--- a/jdk/src/share/classes/java/net/URLConnection.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/net/URLConnection.java Mon May 12 09:37:50 2014 -0700
@@ -704,21 +704,10 @@
* handler for that content type.
* <li>If no content handler factory has yet been set up, or if the
* factory's {@code createContentHandler} method returns
- * {@code null}, then the application loads the class named:
- * <blockquote><pre>
- * sun.net.www.content.<<i>contentType</i>>
- * </pre></blockquote>
- * where <<i>contentType</i>> is formed by taking the
- * content-type string, replacing all slash characters with a
- * {@code period} ('.'), and all other non-alphanumeric characters
- * with the underscore character '{@code _}'. The alphanumeric
- * characters are specifically the 26 uppercase ASCII letters
- * '{@code A}' through '{@code Z}', the 26 lowercase ASCII
- * letters '{@code a}' through '{@code z}', and the 10 ASCII
- * digits '{@code 0}' through '{@code 9}'. If the specified
- * class does not exist, or is not a subclass of
- * {@code ContentHandler}, then an
- * {@code UnknownServiceException} is thrown.
+ * {@code null}, then this method tries to load a content handler
+ * class as defined by {@link java.net.ContentHandler ContentHandler}.
+ * If the class does not exist, or is not a subclass of {@code
+ * ContentHandler}, then an {@code UnknownServiceException} is thrown.
* </ol>
*
* @return the object fetched. The {@code instanceof} operator
--- a/jdk/src/share/classes/java/time/DayOfWeek.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/DayOfWeek.java Mon May 12 09:37:50 2014 -0700
@@ -201,7 +201,7 @@
* Gets the day-of-week {@code int} value.
* <p>
* The values are numbered following the ISO-8601 standard, from 1 (Monday) to 7 (Sunday).
- * See {@link WeekFields#dayOfWeek} for localized week-numbering.
+ * See {@link java.time.temporal.WeekFields#dayOfWeek()} for localized week-numbering.
*
* @return the day-of-week, from 1 (Monday) to 7 (Sunday)
*/
@@ -288,7 +288,7 @@
/**
* Gets the value of the specified field from this day-of-week as an {@code int}.
* <p>
- * This queries this day-of-week for the value for the specified field.
+ * This queries this day-of-week for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -321,7 +321,7 @@
/**
* Gets the value of the specified field from this day-of-week as a {@code long}.
* <p>
- * This queries this day-of-week for the value for the specified field.
+ * This queries this day-of-week for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
@@ -419,7 +419,7 @@
* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
* passing {@link ChronoField#DAY_OF_WEEK} as the field.
* Note that this adjusts forwards or backwards within a Monday to Sunday week.
- * See {@link WeekFields#dayOfWeek} for localized week start days.
+ * See {@link java.time.temporal.WeekFields#dayOfWeek()} for localized week start days.
* See {@code TemporalAdjuster} for other adjusters with more control,
* such as {@code next(MONDAY)}.
* <p>
--- a/jdk/src/share/classes/java/time/Duration.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/Duration.java Mon May 12 09:37:50 2014 -0700
@@ -546,7 +546,7 @@
* They are returned in the order seconds, nanos.
* <p>
* This set can be used in conjunction with {@link #get(TemporalUnit)}
- * to access the entire state of the period.
+ * to access the entire state of the duration.
*
* @return a list containing the seconds and nanos units, not null
*/
@@ -686,8 +686,8 @@
* <p>
* This instance is immutable and unaffected by this method call.
*
- * @param amountToAdd the amount of the period, measured in terms of the unit, positive or negative
- * @param unit the unit that the period is measured in, must have an exact duration, not null
+ * @param amountToAdd the amount to add, measured in terms of the unit, positive or negative
+ * @param unit the unit that the amount is measured in, must have an exact duration, not null
* @return a {@code Duration} based on this duration with the specified duration added, not null
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
@@ -848,8 +848,8 @@
* <p>
* This instance is immutable and unaffected by this method call.
*
- * @param amountToSubtract the amount of the period, measured in terms of the unit, positive or negative
- * @param unit the unit that the period is measured in, must have an exact duration, not null
+ * @param amountToSubtract the amount to subtract, measured in terms of the unit, positive or negative
+ * @param unit the unit that the amount is measured in, must have an exact duration, not null
* @return a {@code Duration} based on this duration with the specified duration subtracted, not null
* @throws ArithmeticException if numeric overflow occurs
*/
--- a/jdk/src/share/classes/java/time/Instant.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/Instant.java Mon May 12 09:37:50 2014 -0700
@@ -530,7 +530,7 @@
/**
* Gets the value of the specified field from this instant as an {@code int}.
* <p>
- * This queries this instant for the value for the specified field.
+ * This queries this instant for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -571,7 +571,7 @@
/**
* Gets the value of the specified field from this instant as a {@code long}.
* <p>
- * This queries this instant for the value for the specified field.
+ * This queries this instant for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
--- a/jdk/src/share/classes/java/time/LocalDate.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/LocalDate.java Mon May 12 09:37:50 2014 -0700
@@ -280,7 +280,7 @@
* @param dayOfYear the day-of-year to represent, from 1 to 366
* @return the local date, not null
* @throws DateTimeException if the value of any field is out of range,
- * or if the day-of-year is invalid for the month-year
+ * or if the day-of-year is invalid for the year
*/
public static LocalDate ofYearDay(int year, int dayOfYear) {
YEAR.checkValidValue(year);
@@ -308,7 +308,7 @@
*
* @param epochDay the Epoch Day to convert, based on the epoch 1970-01-01
* @return the local date, not null
- * @throws DateTimeException if the epoch days exceeds the supported date range
+ * @throws DateTimeException if the epoch day exceeds the supported date range
*/
public static LocalDate ofEpochDay(long epochDay) {
long zeroDay = epochDay + DAYS_0000_TO_1970;
@@ -515,7 +515,7 @@
/**
* Checks if the specified unit is supported.
* <p>
- * This checks if the specified unit can be added to, or subtracted from, this date-time.
+ * This checks if the specified unit can be added to, or subtracted from, this date.
* If false, then calling the {@link #plus(long, TemporalUnit)} and
* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
* <p>
@@ -592,7 +592,7 @@
/**
* Gets the value of the specified field from this date as an {@code int}.
* <p>
- * This queries this date for the value for the specified field.
+ * This queries this date for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -600,7 +600,7 @@
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this date, except {@code EPOCH_DAY} and {@code PROLEPTIC_MONTH}
- * which are too large to fit in an {@code int} and throw a {@code DateTimeException}.
+ * which are too large to fit in an {@code int} and throw an {@code UnsupportedTemporalTypeException}.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
@@ -627,7 +627,7 @@
/**
* Gets the value of the specified field from this date as a {@code long}.
* <p>
- * This queries this date for the value for the specified field.
+ * This queries this date for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
@@ -875,7 +875,9 @@
* <p>
* A simple adjuster might simply set the one of the fields, such as the year field.
* A more complex adjuster might set the date to the last day of the month.
- * A selection of common adjustments is provided in {@link TemporalAdjuster}.
+ * <p>
+ * A selection of common adjustments is provided in
+ * {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.
* These include finding the "last day of the month" and "next Wednesday".
* Key date-time classes also implement the {@code TemporalAdjuster} interface,
* such as {@link Month} and {@link java.time.MonthDay MonthDay}.
@@ -885,7 +887,7 @@
* For example this code returns a date on the last day of July:
* <pre>
* import static java.time.Month.*;
- * import static java.time.temporal.Adjusters.*;
+ * import static java.time.temporal.TemporalAdjusters.*;
*
* result = localDate.with(JULY).with(lastDayOfMonth());
* </pre>
@@ -1041,7 +1043,8 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this date with the year altered.
+ * Returns a copy of this {@code LocalDate} with the year altered.
+ * <p>
* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.
* <p>
* This instance is immutable and unaffected by this method call.
@@ -1059,7 +1062,8 @@
}
/**
- * Returns a copy of this date with the month-of-year altered.
+ * Returns a copy of this {@code LocalDate} with the month-of-year altered.
+ * <p>
* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.
* <p>
* This instance is immutable and unaffected by this method call.
@@ -1077,7 +1081,8 @@
}
/**
- * Returns a copy of this date with the day-of-month altered.
+ * Returns a copy of this {@code LocalDate} with the day-of-month altered.
+ * <p>
* If the resulting date is invalid, an exception is thrown.
* <p>
* This instance is immutable and unaffected by this method call.
@@ -1095,7 +1100,8 @@
}
/**
- * Returns a copy of this date with the day-of-year altered.
+ * Returns a copy of this {@code LocalDate} with the day-of-year altered.
+ * <p>
* If the resulting date is invalid, an exception is thrown.
* <p>
* This instance is immutable and unaffected by this method call.
@@ -1245,7 +1251,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code LocalDate} with the specified period in years added.
+ * Returns a copy of this {@code LocalDate} with the specified number of years added.
* <p>
* This method adds the specified amount to the years field in three steps:
* <ol>
@@ -1273,7 +1279,7 @@
}
/**
- * Returns a copy of this {@code LocalDate} with the specified period in months added.
+ * Returns a copy of this {@code LocalDate} with the specified number of months added.
* <p>
* This method adds the specified amount to the months field in three steps:
* <ol>
@@ -1304,7 +1310,7 @@
}
/**
- * Returns a copy of this {@code LocalDate} with the specified period in weeks added.
+ * Returns a copy of this {@code LocalDate} with the specified number of weeks added.
* <p>
* This method adds the specified amount in weeks to the days field incrementing
* the month and year fields as necessary to ensure the result remains valid.
@@ -1402,11 +1408,11 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code LocalDate} with the specified period in years subtracted.
+ * Returns a copy of this {@code LocalDate} with the specified number of years subtracted.
* <p>
* This method subtracts the specified amount from the years field in three steps:
* <ol>
- * <li>Subtract the input years to the year field</li>
+ * <li>Subtract the input years from the year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the day-of-month to the last valid day if necessary</li>
* </ol>
@@ -1426,11 +1432,11 @@
}
/**
- * Returns a copy of this {@code LocalDate} with the specified period in months subtracted.
+ * Returns a copy of this {@code LocalDate} with the specified number of months subtracted.
* <p>
* This method subtracts the specified amount from the months field in three steps:
* <ol>
- * <li>Subtract the input months to the month-of-year field</li>
+ * <li>Subtract the input months from the month-of-year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the day-of-month to the last valid day if necessary</li>
* </ol>
@@ -1450,7 +1456,7 @@
}
/**
- * Returns a copy of this {@code LocalDate} with the specified period in weeks subtracted.
+ * Returns a copy of this {@code LocalDate} with the specified number of weeks subtracted.
* <p>
* This method subtracts the specified amount in weeks from the days field decrementing
* the month and year fields as necessary to ensure the result remains valid.
--- a/jdk/src/share/classes/java/time/LocalDateTime.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/LocalDateTime.java Mon May 12 09:37:50 2014 -0700
@@ -428,7 +428,7 @@
/**
* Obtains an instance of {@code LocalDateTime} from a temporal object.
* <p>
- * This obtains an offset time based on the specified temporal.
+ * This obtains a local date-time based on the specified temporal.
* A {@code TemporalAccessor} represents an arbitrary set of date and time information,
* which this factory converts to an instance of {@code LocalDateTime}.
* <p>
@@ -656,7 +656,7 @@
/**
* Gets the value of the specified field from this date-time as an {@code int}.
* <p>
- * This queries this date-time for the value for the specified field.
+ * This queries this date-time for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -665,7 +665,7 @@
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this date-time, except {@code NANO_OF_DAY}, {@code MICRO_OF_DAY},
* {@code EPOCH_DAY} and {@code PROLEPTIC_MONTH} which are too large to fit in
- * an {@code int} and throw a {@code DateTimeException}.
+ * an {@code int} and throw a {@code UnsupportedTemporalTypeException}.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
@@ -693,7 +693,7 @@
/**
* Gets the value of the specified field from this date-time as a {@code long}.
* <p>
- * This queries this date-time for the value for the specified field.
+ * This queries this date-time for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
@@ -878,7 +878,9 @@
* <p>
* A simple adjuster might simply set the one of the fields, such as the year field.
* A more complex adjuster might set the date to the last day of the month.
- * A selection of common adjustments is provided in {@link TemporalAdjuster}.
+ * <p>
+ * A selection of common adjustments is provided in
+ * {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.
* These include finding the "last day of the month" and "next Wednesday".
* Key date-time classes also implement the {@code TemporalAdjuster} interface,
* such as {@link Month} and {@link java.time.MonthDay MonthDay}.
@@ -888,7 +890,7 @@
* For example this code returns a date on the last day of July:
* <pre>
* import static java.time.Month.*;
- * import static java.time.temporal.Adjusters.*;
+ * import static java.time.temporal.TemporalAdjusters.*;
*
* result = localDateTime.with(JULY).with(lastDayOfMonth());
* </pre>
@@ -974,6 +976,7 @@
//-----------------------------------------------------------------------
/**
* Returns a copy of this {@code LocalDateTime} with the year altered.
+ * <p>
* The time does not affect the calculation and will be the same in the result.
* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.
* <p>
@@ -989,6 +992,7 @@
/**
* Returns a copy of this {@code LocalDateTime} with the month-of-year altered.
+ * <p>
* The time does not affect the calculation and will be the same in the result.
* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.
* <p>
@@ -1004,7 +1008,8 @@
/**
* Returns a copy of this {@code LocalDateTime} with the day-of-month altered.
- * If the resulting {@code LocalDateTime} is invalid, an exception is thrown.
+ * <p>
+ * If the resulting date-time is invalid, an exception is thrown.
* The time does not affect the calculation and will be the same in the result.
* <p>
* This instance is immutable and unaffected by this method call.
@@ -1020,7 +1025,8 @@
/**
* Returns a copy of this {@code LocalDateTime} with the day-of-year altered.
- * If the resulting {@code LocalDateTime} is invalid, an exception is thrown.
+ * <p>
+ * If the resulting date-time is invalid, an exception is thrown.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1035,7 +1041,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code LocalDateTime} with the hour-of-day value altered.
+ * Returns a copy of this {@code LocalDateTime} with the hour-of-day altered.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1049,7 +1055,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the minute-of-hour value altered.
+ * Returns a copy of this {@code LocalDateTime} with the minute-of-hour altered.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1063,7 +1069,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the second-of-minute value altered.
+ * Returns a copy of this {@code LocalDateTime} with the second-of-minute altered.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1077,7 +1083,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the nano-of-second value altered.
+ * Returns a copy of this {@code LocalDateTime} with the nano-of-second altered.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1109,7 +1115,7 @@
* @param unit the unit to truncate to, not null
* @return a {@code LocalDateTime} based on this date-time with the time truncated, not null
* @throws DateTimeException if unable to truncate
- * @throws UnsupportedTemporalTypeException if the field is not supported
+ * @throws UnsupportedTemporalTypeException if the unit is not supported
*/
public LocalDateTime truncatedTo(TemporalUnit unit) {
return with(date, time.truncatedTo(unit));
@@ -1192,7 +1198,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in years added.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of years added.
* <p>
* This method adds the specified amount to the years field in three steps:
* <ol>
@@ -1217,7 +1223,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in months added.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of months added.
* <p>
* This method adds the specified amount to the months field in three steps:
* <ol>
@@ -1242,7 +1248,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in weeks added.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of weeks added.
* <p>
* This method adds the specified amount in weeks to the days field incrementing
* the month and year fields as necessary to ensure the result remains valid.
@@ -1262,7 +1268,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in days added.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of days added.
* <p>
* This method adds the specified amount to the days field incrementing the
* month and year fields as necessary to ensure the result remains valid.
@@ -1283,7 +1289,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in hours added.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of hours added.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1296,7 +1302,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in minutes added.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of minutes added.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1309,7 +1315,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in seconds added.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of seconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1322,7 +1328,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in nanoseconds added.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of nanoseconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1391,7 +1397,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in years subtracted.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of years subtracted.
* <p>
* This method subtracts the specified amount from the years field in three steps:
* <ol>
@@ -1415,7 +1421,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in months subtracted.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of months subtracted.
* <p>
* This method subtracts the specified amount from the months field in three steps:
* <ol>
@@ -1439,7 +1445,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in weeks subtracted.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of weeks subtracted.
* <p>
* This method subtracts the specified amount in weeks from the days field decrementing
* the month and year fields as necessary to ensure the result remains valid.
@@ -1458,9 +1464,9 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in days subtracted.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of days subtracted.
* <p>
- * This method subtracts the specified amount from the days field incrementing the
+ * This method subtracts the specified amount from the days field decrementing the
* month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
* <p>
@@ -1478,7 +1484,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in hours subtracted.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of hours subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1491,7 +1497,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in minutes subtracted.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of minutes subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1504,7 +1510,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in seconds subtracted.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of seconds subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1517,7 +1523,7 @@
}
/**
- * Returns a copy of this {@code LocalDateTime} with the specified period in nanoseconds subtracted.
+ * Returns a copy of this {@code LocalDateTime} with the specified number of nanoseconds subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1575,7 +1581,7 @@
* what the result of this method will be.
* <p>
* The result of this method is obtained by invoking the
- * {@link java.time.temporal.TemporalQuery#queryFrom(TemporalAccessor)} method on the
+ * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
* specified query passing {@code this} as the argument.
*
* @param <R> the type of the result
--- a/jdk/src/share/classes/java/time/LocalTime.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/LocalTime.java Mon May 12 09:37:50 2014 -0700
@@ -93,7 +93,7 @@
import java.util.Objects;
/**
- * A time without time-zone in the ISO-8601 calendar system,
+ * A time without a time-zone in the ISO-8601 calendar system,
* such as {@code 10:15:30}.
* <p>
* {@code LocalTime} is an immutable date-time object that represents a time,
@@ -101,7 +101,7 @@
* Time is represented to nanosecond precision.
* For example, the value "13:45.30.123456789" can be stored in a {@code LocalTime}.
* <p>
- * It does not store or represent a date or time-zone.
+ * This class does not store or represent a date or time-zone.
* Instead, it is a description of the local time as seen on a wall clock.
* It cannot represent an instant on the time-line without additional information
* such as an offset or time-zone.
@@ -280,7 +280,7 @@
return ofNanoOfDay(secsOfDay * NANOS_PER_SECOND + now.getNano());
}
- //------------------------get-----------------------------------------------
+ //-----------------------------------------------------------------------
/**
* Obtains an instance of {@code LocalTime} from an hour and minute.
* <p>
@@ -395,7 +395,7 @@
* on extracting the {@link ChronoField#NANO_OF_DAY NANO_OF_DAY} field.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
- * allowing it to be used in queries via method reference, {@code LocalTime::from}.
+ * allowing it to be used as a query via method reference, {@code LocalTime::from}.
*
* @param temporal the temporal object to convert, not null
* @return the local time, not null
@@ -418,7 +418,7 @@
* The string must represent a valid time and is parsed using
* {@link java.time.format.DateTimeFormatter#ISO_LOCAL_TIME}.
*
- * @param text the text to parse such as "10:15:30", not null
+ * @param text the text to parse such as "10:15:30", not null
* @return the parsed local time, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
@@ -524,7 +524,7 @@
/**
* Checks if the specified unit is supported.
* <p>
- * This checks if the specified unit can be added to, or subtracted from, this date-time.
+ * This checks if the specified unit can be added to, or subtracted from, this time.
* If false, then calling the {@link #plus(long, TemporalUnit)} and
* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
* <p>
@@ -589,7 +589,7 @@
/**
* Gets the value of the specified field from this time as an {@code int}.
* <p>
- * This queries this time for the value for the specified field.
+ * This queries this time for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -597,7 +597,7 @@
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this time, except {@code NANO_OF_DAY} and {@code MICRO_OF_DAY}
- * which are too large to fit in an {@code int} and throw a {@code DateTimeException}.
+ * which are too large to fit in an {@code int} and throw a {@code UnsupportedTemporalTypeException}.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
@@ -624,7 +624,7 @@
/**
* Gets the value of the specified field from this time as a {@code long}.
* <p>
- * This queries this time for the value for the specified field.
+ * This queries this time for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
@@ -858,7 +858,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code LocalTime} with the hour-of-day value altered.
+ * Returns a copy of this {@code LocalTime} with the hour-of-day altered.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -875,7 +875,7 @@
}
/**
- * Returns a copy of this {@code LocalTime} with the minute-of-hour value altered.
+ * Returns a copy of this {@code LocalTime} with the minute-of-hour altered.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -892,7 +892,7 @@
}
/**
- * Returns a copy of this {@code LocalTime} with the second-of-minute value altered.
+ * Returns a copy of this {@code LocalTime} with the second-of-minute altered.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -909,7 +909,7 @@
}
/**
- * Returns a copy of this {@code LocalTime} with the nano-of-second value altered.
+ * Returns a copy of this {@code LocalTime} with the nano-of-second altered.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -929,7 +929,7 @@
/**
* Returns a copy of this {@code LocalTime} with the time truncated.
* <p>
- * Truncating the time returns a copy of the original time with fields
+ * Truncation returns a copy of the original time with fields
* smaller than the specified unit set to zero.
* For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit
* will set the second-of-minute and nano-of-second field to zero.
@@ -1059,7 +1059,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code LocalTime} with the specified period in hours added.
+ * Returns a copy of this {@code LocalTime} with the specified number of hours added.
* <p>
* This adds the specified number of hours to this time, returning a new time.
* The calculation wraps around midnight.
@@ -1078,7 +1078,7 @@
}
/**
- * Returns a copy of this {@code LocalTime} with the specified period in minutes added.
+ * Returns a copy of this {@code LocalTime} with the specified number of minutes added.
* <p>
* This adds the specified number of minutes to this time, returning a new time.
* The calculation wraps around midnight.
@@ -1103,7 +1103,7 @@
}
/**
- * Returns a copy of this {@code LocalTime} with the specified period in seconds added.
+ * Returns a copy of this {@code LocalTime} with the specified number of seconds added.
* <p>
* This adds the specified number of seconds to this time, returning a new time.
* The calculation wraps around midnight.
@@ -1130,7 +1130,7 @@
}
/**
- * Returns a copy of this {@code LocalTime} with the specified period in nanoseconds added.
+ * Returns a copy of this {@code LocalTime} with the specified number of nanoseconds added.
* <p>
* This adds the specified number of nanoseconds to this time, returning a new time.
* The calculation wraps around midnight.
@@ -1208,7 +1208,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code LocalTime} with the specified period in hours subtracted.
+ * Returns a copy of this {@code LocalTime} with the specified number of hours subtracted.
* <p>
* This subtracts the specified number of hours from this time, returning a new time.
* The calculation wraps around midnight.
@@ -1223,7 +1223,7 @@
}
/**
- * Returns a copy of this {@code LocalTime} with the specified period in minutes subtracted.
+ * Returns a copy of this {@code LocalTime} with the specified number of minutes subtracted.
* <p>
* This subtracts the specified number of minutes from this time, returning a new time.
* The calculation wraps around midnight.
@@ -1238,7 +1238,7 @@
}
/**
- * Returns a copy of this {@code LocalTime} with the specified period in seconds subtracted.
+ * Returns a copy of this {@code LocalTime} with the specified number of seconds subtracted.
* <p>
* This subtracts the specified number of seconds from this time, returning a new time.
* The calculation wraps around midnight.
@@ -1253,7 +1253,7 @@
}
/**
- * Returns a copy of this {@code LocalTime} with the specified period in nanoseconds subtracted.
+ * Returns a copy of this {@code LocalTime} with the specified number of nanoseconds subtracted.
* <p>
* This subtracts the specified number of nanoseconds from this time, returning a new time.
* The calculation wraps around midnight.
@@ -1470,14 +1470,13 @@
//-----------------------------------------------------------------------
/**
- * Compares this {@code LocalTime} to another time.
+ * Compares this time to another time.
* <p>
* The comparison is based on the time-line position of the local times within a day.
* It is "consistent with equals", as defined by {@link Comparable}.
*
* @param other the other time to compare to, not null
* @return the comparator value, negative if less, positive if greater
- * @throws NullPointerException if {@code other} is null
*/
@Override
public int compareTo(LocalTime other) {
@@ -1495,26 +1494,24 @@
}
/**
- * Checks if this {@code LocalTime} is after the specified time.
+ * Checks if this time is after the specified time.
* <p>
* The comparison is based on the time-line position of the time within a day.
*
* @param other the other time to compare to, not null
* @return true if this is after the specified time
- * @throws NullPointerException if {@code other} is null
*/
public boolean isAfter(LocalTime other) {
return compareTo(other) > 0;
}
/**
- * Checks if this {@code LocalTime} is before the specified time.
+ * Checks if this time is before the specified time.
* <p>
* The comparison is based on the time-line position of the time within a day.
*
* @param other the other time to compare to, not null
* @return true if this point is before the specified time
- * @throws NullPointerException if {@code other} is null
*/
public boolean isBefore(LocalTime other) {
return compareTo(other) < 0;
--- a/jdk/src/share/classes/java/time/Month.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/Month.java Mon May 12 09:37:50 2014 -0700
@@ -202,7 +202,7 @@
* chronology, or can be converted to a {@code LocalDate}.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
- * allowing it to be used in queries via method reference, {@code Month::from}.
+ * allowing it to be used as a query via method reference, {@code Month::from}.
*
* @param temporal the temporal object to convert, not null
* @return the month-of-year, not null
@@ -315,7 +315,7 @@
/**
* Gets the value of the specified field from this month-of-year as an {@code int}.
* <p>
- * This queries this month for the value for the specified field.
+ * This queries this month for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -348,7 +348,7 @@
/**
* Gets the value of the specified field from this month-of-year as a {@code long}.
* <p>
- * This queries this month for the value for the specified field.
+ * This queries this month for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
--- a/jdk/src/share/classes/java/time/MonthDay.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/MonthDay.java Mon May 12 09:37:50 2014 -0700
@@ -90,8 +90,8 @@
* A month-day in the ISO-8601 calendar system, such as {@code --12-03}.
* <p>
* {@code MonthDay} is an immutable date-time object that represents the combination
- * of a year and month. Any field that can be derived from a month and day, such as
- * quarter-of-year, can be obtained.
+ * of a month and day-of-month. Any field that can be derived from a month and day,
+ * such as quarter-of-year, can be obtained.
* <p>
* This class does not store or represent a year, time or time-zone.
* For example, the value "December 3rd" can be stored in a {@code MonthDay}.
@@ -154,7 +154,7 @@
/**
* Obtains the current month-day from the system clock in the default time-zone.
* <p>
- * This will query the {@link java.time.Clock#systemDefaultZone() system clock} in the default
+ * This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current month-day.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
@@ -169,7 +169,7 @@
/**
* Obtains the current month-day from the system clock in the specified time-zone.
* <p>
- * This will query the {@link Clock#system(java.time.ZoneId) system clock} to obtain the current month-day.
+ * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current month-day.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
@@ -258,7 +258,7 @@
* chronology, or can be converted to a {@code LocalDate}.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
- * allowing it to be used in queries via method reference, {@code MonthDay::from}.
+ * allowing it to be used as a query via method reference, {@code MonthDay::from}.
*
* @param temporal the temporal object to convert, not null
* @return the month-day, not null
@@ -389,7 +389,7 @@
/**
* Gets the value of the specified field from this month-day as an {@code int}.
* <p>
- * This queries this month-day for the value for the specified field.
+ * This queries this month-day for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -420,7 +420,7 @@
/**
* Gets the value of the specified field from this month-day as a {@code long}.
* <p>
- * This queries this month-day for the value for the specified field.
+ * This queries this month-day for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
@@ -501,7 +501,7 @@
* This method checks whether this month and day and the input year form
* a valid date. This can only return false for February 29th.
*
- * @param year the year to validate, an out of range value returns false
+ * @param year the year to validate
* @return true if the year is valid for this month-day
* @see Year#isValidMonthDay(MonthDay)
*/
@@ -685,7 +685,7 @@
}
/**
- * Is this month-day after the specified month-day.
+ * Checks if this month-day is after the specified month-day.
*
* @param other the other month-day to compare to, not null
* @return true if this is after the specified month-day
@@ -695,7 +695,7 @@
}
/**
- * Is this month-day before the specified month-day.
+ * Checks if this month-day is before the specified month-day.
*
* @param other the other month-day to compare to, not null
* @return true if this point is before the specified month-day
--- a/jdk/src/share/classes/java/time/OffsetDateTime.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/OffsetDateTime.java Mon May 12 09:37:50 2014 -0700
@@ -199,7 +199,7 @@
/**
* Obtains the current date-time from the system clock in the default time-zone.
* <p>
- * This will query the {@link java.time.Clock#systemDefaultZone() system clock} in the default
+ * This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current date-time.
* The offset will be calculated from the time-zone in the clock.
* <p>
@@ -215,7 +215,7 @@
/**
* Obtains the current date-time from the system clock in the specified time-zone.
* <p>
- * This will query the {@link Clock#system(java.time.ZoneId) system clock} to obtain the current date-time.
+ * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date-time.
* Specifying the time-zone avoids dependence on the default time-zone.
* The offset will be calculated from the specified time-zone.
* <p>
@@ -345,7 +345,7 @@
* those fields that are equivalent to the relevant objects.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
- * allowing it to be used in queries via method reference, {@code OffsetDateTime::from}.
+ * allowing it to be used as a query via method reference, {@code OffsetDateTime::from}.
*
* @param temporal the temporal object to convert, not null
* @return the offset date-time, not null
@@ -566,7 +566,7 @@
/**
* Gets the value of the specified field from this date-time as an {@code int}.
* <p>
- * This queries this date-time for the value for the specified field.
+ * This queries this date-time for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -575,7 +575,7 @@
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this date-time, except {@code NANO_OF_DAY}, {@code MICRO_OF_DAY},
* {@code EPOCH_DAY}, {@code PROLEPTIC_MONTH} and {@code INSTANT_SECONDS} which are too
- * large to fit in an {@code int} and throw a {@code DateTimeException}.
+ * large to fit in an {@code int} and throw a {@code UnsupportedTemporalTypeException}.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
@@ -608,7 +608,7 @@
/**
* Gets the value of the specified field from this date-time as a {@code long}.
* <p>
- * This queries this date-time for the value for the specified field.
+ * This queries this date-time for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
@@ -703,7 +703,7 @@
//-----------------------------------------------------------------------
/**
- * Gets the {@code LocalDateTime} part of this offset date-time.
+ * Gets the {@code LocalDateTime} part of this date-time.
* <p>
* This returns a {@code LocalDateTime} with the same year, month, day and time
* as this date-time.
@@ -795,10 +795,10 @@
/**
* Gets the day-of-week field, which is an enum {@code DayOfWeek}.
* <p>
- * This method returns the enum {@link java.time.DayOfWeek} for the day-of-week.
+ * This method returns the enum {@link DayOfWeek} for the day-of-week.
* This avoids confusion as to what {@code int} values mean.
* If you need access to the primitive {@code int} value then the enum
- * provides the {@link java.time.DayOfWeek#getValue() int value}.
+ * provides the {@link DayOfWeek#getValue() int value}.
* <p>
* Additional information can be obtained from the {@code DayOfWeek}.
* This includes textual names of the values.
@@ -868,7 +868,8 @@
* <p>
* A simple adjuster might simply set the one of the fields, such as the year field.
* A more complex adjuster might set the date to the last day of the month.
- * A selection of common adjustments is provided in {@link TemporalAdjuster}.
+ * A selection of common adjustments is provided in
+ * {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.
* These include finding the "last day of the month" and "next Wednesday".
* Key date-time classes also implement the {@code TemporalAdjuster} interface,
* such as {@link Month} and {@link java.time.MonthDay MonthDay}.
@@ -878,7 +879,7 @@
* For example this code returns a date on the last day of July:
* <pre>
* import static java.time.Month.*;
- * import static java.time.temporal.Adjusters.*;
+ * import static java.time.temporal.TemporalAdjusters.*;
*
* result = offsetDateTime.with(JULY).with(lastDayOfMonth());
* </pre>
@@ -920,7 +921,7 @@
/**
* Returns a copy of this date-time with the specified field set to a new value.
* <p>
- * TThis returns an {@code OffsetDateTime}, based on this one, with the value
+ * This returns an {@code OffsetDateTime}, based on this one, with the value
* for the specified field changed.
* This can be used to change any supported field, such as the year, month or day-of-month.
* If it is not possible to set the value, because the field is not supported or for
@@ -979,7 +980,8 @@
//-----------------------------------------------------------------------
/**
* Returns a copy of this {@code OffsetDateTime} with the year altered.
- * The offset does not affect the calculation and will be the same in the result.
+ * <p>
+ * The time and offset do not affect the calculation and will be the same in the result.
* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.
* <p>
* This instance is immutable and unaffected by this method call.
@@ -994,7 +996,8 @@
/**
* Returns a copy of this {@code OffsetDateTime} with the month-of-year altered.
- * The offset does not affect the calculation and will be the same in the result.
+ * <p>
+ * The time and offset do not affect the calculation and will be the same in the result.
* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.
* <p>
* This instance is immutable and unaffected by this method call.
@@ -1009,8 +1012,9 @@
/**
* Returns a copy of this {@code OffsetDateTime} with the day-of-month altered.
+ * <p>
* If the resulting {@code OffsetDateTime} is invalid, an exception is thrown.
- * The offset does not affect the calculation and will be the same in the result.
+ * The time and offset do not affect the calculation and will be the same in the result.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1025,6 +1029,8 @@
/**
* Returns a copy of this {@code OffsetDateTime} with the day-of-year altered.
+ * <p>
+ * The time and offset do not affect the calculation and will be the same in the result.
* If the resulting {@code OffsetDateTime} is invalid, an exception is thrown.
* <p>
* This instance is immutable and unaffected by this method call.
@@ -1040,9 +1046,9 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code OffsetDateTime} with the hour-of-day value altered.
+ * Returns a copy of this {@code OffsetDateTime} with the hour-of-day altered.
* <p>
- * The offset does not affect the calculation and will be the same in the result.
+ * The date and offset do not affect the calculation and will be the same in the result.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1055,9 +1061,9 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the minute-of-hour value altered.
+ * Returns a copy of this {@code OffsetDateTime} with the minute-of-hour altered.
* <p>
- * The offset does not affect the calculation and will be the same in the result.
+ * The date and offset do not affect the calculation and will be the same in the result.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1070,9 +1076,9 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the second-of-minute value altered.
+ * Returns a copy of this {@code OffsetDateTime} with the second-of-minute altered.
* <p>
- * The offset does not affect the calculation and will be the same in the result.
+ * The date and offset do not affect the calculation and will be the same in the result.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1085,15 +1091,15 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the nano-of-second value altered.
+ * Returns a copy of this {@code OffsetDateTime} with the nano-of-second altered.
* <p>
- * The offset does not affect the calculation and will be the same in the result.
+ * The date and offset do not affect the calculation and will be the same in the result.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param nanoOfSecond the nano-of-second to set in the result, from 0 to 999,999,999
* @return an {@code OffsetDateTime} based on this date-time with the requested nanosecond, not null
- * @throws DateTimeException if the nanos value is invalid
+ * @throws DateTimeException if the nano value is invalid
*/
public OffsetDateTime withNano(int nanoOfSecond) {
return with(dateTime.withNano(nanoOfSecond), offset);
@@ -1187,7 +1193,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in years added.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of years added.
* <p>
* This method adds the specified amount to the years field in three steps:
* <ol>
@@ -1211,7 +1217,7 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in months added.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of months added.
* <p>
* This method adds the specified amount to the months field in three steps:
* <ol>
@@ -1235,13 +1241,13 @@
}
/**
- * Returns a copy of this OffsetDateTime with the specified period in weeks added.
+ * Returns a copy of this OffsetDateTime with the specified number of weeks added.
* <p>
* This method adds the specified amount in weeks to the days field incrementing
* the month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
* <p>
- * For example, 2008-12-31 plus one week would result in the 2009-01-07.
+ * For example, 2008-12-31 plus one week would result in 2009-01-07.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1254,13 +1260,13 @@
}
/**
- * Returns a copy of this OffsetDateTime with the specified period in days added.
+ * Returns a copy of this OffsetDateTime with the specified number of days added.
* <p>
* This method adds the specified amount to the days field incrementing the
* month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
* <p>
- * For example, 2008-12-31 plus one day would result in the 2009-01-01.
+ * For example, 2008-12-31 plus one day would result in 2009-01-01.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1273,7 +1279,7 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in hours added.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of hours added.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1286,7 +1292,7 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in minutes added.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of minutes added.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1299,7 +1305,7 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in seconds added.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of seconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1312,7 +1318,7 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in nanoseconds added.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of nanoseconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1376,11 +1382,11 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in years subtracted.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of years subtracted.
* <p>
* This method subtracts the specified amount from the years field in three steps:
* <ol>
- * <li>Subtract the input years to the year field</li>
+ * <li>Subtract the input years from the year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the day-of-month to the last valid day if necessary</li>
* </ol>
@@ -1400,11 +1406,11 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in months subtracted.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of months subtracted.
* <p>
* This method subtracts the specified amount from the months field in three steps:
* <ol>
- * <li>Subtract the input months to the month-of-year field</li>
+ * <li>Subtract the input months from the month-of-year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the day-of-month to the last valid day if necessary</li>
* </ol>
@@ -1424,13 +1430,13 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in weeks subtracted.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of weeks subtracted.
* <p>
* This method subtracts the specified amount in weeks from the days field decrementing
* the month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
* <p>
- * For example, 2008-12-31 minus one week would result in the 2009-01-07.
+ * For example, 2008-12-31 minus one week would result in 2009-01-07.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1443,13 +1449,13 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in days subtracted.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of days subtracted.
* <p>
- * This method subtracts the specified amount from the days field incrementing the
+ * This method subtracts the specified amount from the days field decrementing the
* month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
* <p>
- * For example, 2008-12-31 minus one day would result in the 2009-01-01.
+ * For example, 2008-12-31 minus one day would result in 2009-01-01.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1462,7 +1468,7 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in hours subtracted.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of hours subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1475,7 +1481,7 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in minutes subtracted.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of minutes subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1488,7 +1494,7 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in seconds subtracted.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of seconds subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1501,7 +1507,7 @@
}
/**
- * Returns a copy of this {@code OffsetDateTime} with the specified period in nanoseconds subtracted.
+ * Returns a copy of this {@code OffsetDateTime} with the specified number of nanoseconds subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1598,7 +1604,7 @@
* objects in terms of a single {@code TemporalUnit}.
* The start and end points are {@code this} and the specified date-time.
* The result will be negative if the end is before the start.
- * For example, the period in days between two date-times can be calculated
+ * For example, the amount in days between two date-times can be calculated
* using {@code startDateTime.until(endDateTime, DAYS)}.
* <p>
* The {@code Temporal} passed to this method is converted to a
@@ -1608,7 +1614,7 @@
* <p>
* The calculation returns a whole number, representing the number of
* complete units between the two date-times.
- * For example, the period in months between 2012-06-15T00:00Z and 2012-08-14T23:59Z
+ * For example, the amount in months between 2012-06-15T00:00Z and 2012-08-14T23:59Z
* will only be one month as it is one minute short of two months.
* <p>
* There are two equivalent ways of using this method.
@@ -1769,7 +1775,7 @@
//-----------------------------------------------------------------------
/**
- * Compares this {@code OffsetDateTime} to another date-time.
+ * Compares this date-time to another date-time.
* <p>
* The comparison is based on the instant then on the local date-time.
* It is "consistent with equals", as defined by {@link Comparable}.
--- a/jdk/src/share/classes/java/time/OffsetTime.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/OffsetTime.java Mon May 12 09:37:50 2014 -0700
@@ -153,14 +153,14 @@
/**
* Obtains the current time from the system clock in the default time-zone.
* <p>
- * This will query the {@link java.time.Clock#systemDefaultZone() system clock} in the default
+ * This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current time.
* The offset will be calculated from the time-zone in the clock.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
- * @return the current time using the system clock, not null
+ * @return the current time using the system clock and default time-zone, not null
*/
public static OffsetTime now() {
return now(Clock.systemDefaultZone());
@@ -169,7 +169,7 @@
/**
* Obtains the current time from the system clock in the specified time-zone.
* <p>
- * This will query the {@link Clock#system(java.time.ZoneId) system clock} to obtain the current time.
+ * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current time.
* Specifying the time-zone avoids dependence on the default time-zone.
* The offset will be calculated from the specified time-zone.
* <p>
@@ -277,7 +277,7 @@
* those fields that are equivalent to the relevant objects.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
- * allowing it to be used in queries via method reference, {@code OffsetTime::from}.
+ * allowing it to be used as a query via method reference, {@code OffsetTime::from}.
*
* @param temporal the temporal object to convert, not null
* @return the offset time, not null
@@ -402,7 +402,7 @@
/**
* Checks if the specified unit is supported.
* <p>
- * This checks if the specified unit can be added to, or subtracted from, this date-time.
+ * This checks if the specified unit can be added to, or subtracted from, this offset-time.
* If false, then calling the {@link #plus(long, TemporalUnit)} and
* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
* <p>
@@ -473,7 +473,7 @@
/**
* Gets the value of the specified field from this time as an {@code int}.
* <p>
- * This queries this time for the value for the specified field.
+ * This queries this time for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -481,7 +481,7 @@
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this time, except {@code NANO_OF_DAY} and {@code MICRO_OF_DAY}
- * which are too large to fit in an {@code int} and throw a {@code DateTimeException}.
+ * which are too large to fit in an {@code int} and throw a {@code UnsupportedTemporalTypeException}.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
@@ -505,7 +505,7 @@
/**
* Gets the value of the specified field from this time as a {@code long}.
* <p>
- * This queries this time for the value for the specified field.
+ * This queries this time for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
@@ -575,7 +575,7 @@
* <p>
* This method returns an object with the specified {@code ZoneOffset} and a {@code LocalTime}
* adjusted by the difference between the two offsets.
- * This will result in the old and new objects representing the same instant an an implied day.
+ * This will result in the old and new objects representing the same instant on an implied day.
* This is useful for finding the local time in a different offset.
* For example, if this time represents {@code 10:30+02:00} and the offset specified is
* {@code +03:00}, then this method will return {@code 11:30+03:00}.
@@ -737,7 +737,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code OffsetTime} with the hour-of-day value altered.
+ * Returns a copy of this {@code OffsetTime} with the hour-of-day altered.
* <p>
* The offset does not affect the calculation and will be the same in the result.
* <p>
@@ -752,7 +752,7 @@
}
/**
- * Returns a copy of this {@code OffsetTime} with the minute-of-hour value altered.
+ * Returns a copy of this {@code OffsetTime} with the minute-of-hour altered.
* <p>
* The offset does not affect the calculation and will be the same in the result.
* <p>
@@ -767,7 +767,7 @@
}
/**
- * Returns a copy of this {@code OffsetTime} with the second-of-minute value altered.
+ * Returns a copy of this {@code OffsetTime} with the second-of-minute altered.
* <p>
* The offset does not affect the calculation and will be the same in the result.
* <p>
@@ -782,7 +782,7 @@
}
/**
- * Returns a copy of this {@code OffsetTime} with the nano-of-second value altered.
+ * Returns a copy of this {@code OffsetTime} with the nano-of-second altered.
* <p>
* The offset does not affect the calculation and will be the same in the result.
* <p>
@@ -884,7 +884,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code OffsetTime} with the specified period in hours added.
+ * Returns a copy of this {@code OffsetTime} with the specified number of hours added.
* <p>
* This adds the specified number of hours to this time, returning a new time.
* The calculation wraps around midnight.
@@ -899,7 +899,7 @@
}
/**
- * Returns a copy of this {@code OffsetTime} with the specified period in minutes added.
+ * Returns a copy of this {@code OffsetTime} with the specified number of minutes added.
* <p>
* This adds the specified number of minutes to this time, returning a new time.
* The calculation wraps around midnight.
@@ -914,7 +914,7 @@
}
/**
- * Returns a copy of this {@code OffsetTime} with the specified period in seconds added.
+ * Returns a copy of this {@code OffsetTime} with the specified number of seconds added.
* <p>
* This adds the specified number of seconds to this time, returning a new time.
* The calculation wraps around midnight.
@@ -929,7 +929,7 @@
}
/**
- * Returns a copy of this {@code OffsetTime} with the specified period in nanoseconds added.
+ * Returns a copy of this {@code OffsetTime} with the specified number of nanoseconds added.
* <p>
* This adds the specified number of nanoseconds to this time, returning a new time.
* The calculation wraps around midnight.
@@ -995,7 +995,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code OffsetTime} with the specified period in hours subtracted.
+ * Returns a copy of this {@code OffsetTime} with the specified number of hours subtracted.
* <p>
* This subtracts the specified number of hours from this time, returning a new time.
* The calculation wraps around midnight.
@@ -1010,7 +1010,7 @@
}
/**
- * Returns a copy of this {@code OffsetTime} with the specified period in minutes subtracted.
+ * Returns a copy of this {@code OffsetTime} with the specified number of minutes subtracted.
* <p>
* This subtracts the specified number of minutes from this time, returning a new time.
* The calculation wraps around midnight.
@@ -1025,7 +1025,7 @@
}
/**
- * Returns a copy of this {@code OffsetTime} with the specified period in seconds subtracted.
+ * Returns a copy of this {@code OffsetTime} with the specified number of seconds subtracted.
* <p>
* This subtracts the specified number of seconds from this time, returning a new time.
* The calculation wraps around midnight.
@@ -1040,7 +1040,7 @@
}
/**
- * Returns a copy of this {@code OffsetTime} with the specified period in nanoseconds subtracted.
+ * Returns a copy of this {@code OffsetTime} with the specified number of nanoseconds subtracted.
* <p>
* This subtracts the specified number of nanoseconds from this time, returning a new time.
* The calculation wraps around midnight.
@@ -1130,7 +1130,7 @@
* objects in terms of a single {@code TemporalUnit}.
* The start and end points are {@code this} and the specified time.
* The result will be negative if the end is before the start.
- * For example, the period in hours between two times can be calculated
+ * For example, the amount in hours between two times can be calculated
* using {@code startTime.until(endTime, HOURS)}.
* <p>
* The {@code Temporal} passed to this method is converted to a
@@ -1140,7 +1140,7 @@
* <p>
* The calculation returns a whole number, representing the number of
* complete units between the two times.
- * For example, the period in hours between 11:30Z and 13:29Z will only
+ * For example, the amount in hours between 11:30Z and 13:29Z will only
* be one hour as it is one minute short of two hours.
* <p>
* There are two equivalent ways of using this method.
@@ -1165,7 +1165,7 @@
* <p>
* This instance is immutable and unaffected by this method call.
*
- * @param endExclusive the end date, exclusive, which is converted to an {@code OffsetTime}, not null
+ * @param endExclusive the end time, exclusive, which is converted to an {@code OffsetTime}, not null
* @param unit the unit to measure the amount in, not null
* @return the amount of time between this time and the end time
* @throws DateTimeException if the amount cannot be calculated, or the end
@@ -1258,7 +1258,6 @@
*
* @param other the other time to compare to, not null
* @return the comparator value, negative if less, positive if greater
- * @throws NullPointerException if {@code other} is null
*/
@Override
public int compareTo(OffsetTime other) {
--- a/jdk/src/share/classes/java/time/Period.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/Period.java Mon May 12 09:37:50 2014 -0700
@@ -616,7 +616,7 @@
* <p>
* This instance is immutable and unaffected by this method call.
*
- * @param amountToAdd the period to add, not null
+ * @param amountToAdd the amount to add, not null
* @return a {@code Period} based on this period with the requested period added, not null
* @throws DateTimeException if the specified amount has a non-ISO chronology or
* contains an invalid unit
@@ -705,7 +705,7 @@
* <p>
* This instance is immutable and unaffected by this method call.
*
- * @param amountToSubtract the period to subtract, not null
+ * @param amountToSubtract the amount to subtract, not null
* @return a {@code Period} based on this period with the requested period subtracted, not null
* @throws DateTimeException if the specified amount has a non-ISO chronology or
* contains an invalid unit
--- a/jdk/src/share/classes/java/time/Year.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/Year.java Mon May 12 09:37:50 2014 -0700
@@ -164,7 +164,7 @@
/**
* Obtains the current year from the system clock in the default time-zone.
* <p>
- * This will query the {@link java.time.Clock#systemDefaultZone() system clock} in the default
+ * This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current year.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
@@ -179,7 +179,7 @@
/**
* Obtains the current year from the system clock in the specified time-zone.
* <p>
- * This will query the {@link Clock#system(java.time.ZoneId) system clock} to obtain the current year.
+ * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current year.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
@@ -240,7 +240,7 @@
* chronology, or can be converted to a {@code LocalDate}.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
- * allowing it to be used in queries via method reference, {@code Year::from}.
+ * allowing it to be used as a query via method reference, {@code Year::from}.
*
* @param temporal the temporal object to convert, not null
* @return the year, not null
@@ -375,7 +375,7 @@
/**
* Checks if the specified unit is supported.
* <p>
- * This checks if the specified unit can be added to, or subtracted from, this date-time.
+ * This checks if the specified unit can be added to, or subtracted from, this year.
* If false, then calling the {@link #plus(long, TemporalUnit)} and
* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
* <p>
@@ -441,7 +441,7 @@
/**
* Gets the value of the specified field from this year as an {@code int}.
* <p>
- * This queries this year for the value for the specified field.
+ * This queries this year for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -472,7 +472,7 @@
/**
* Gets the value of the specified field from this year as a {@code long}.
* <p>
- * This queries this year for the value for the specified field.
+ * This queries this year for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
@@ -720,13 +720,13 @@
}
/**
- * Returns a copy of this year with the specified number of years added.
+ * Returns a copy of this {@code Year} with the specified number of years added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToAdd the years to add, may be negative
- * @return a {@code Year} based on this year with the period added, not null
- * @throws DateTimeException if the result exceeds the supported year range
+ * @return a {@code Year} based on this year with the years added, not null
+ * @throws DateTimeException if the result exceeds the supported range
*/
public Year plusYears(long yearsToAdd) {
if (yearsToAdd == 0) {
@@ -786,13 +786,13 @@
}
/**
- * Returns a copy of this year with the specified number of years subtracted.
+ * Returns a copy of this {@code Year} with the specified number of years subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToSubtract the years to subtract, may be negative
- * @return a {@code Year} based on this year with the period subtracted, not null
- * @throws DateTimeException if the result exceeds the supported year range
+ * @return a {@code Year} based on this year with the year subtracted, not null
+ * @throws DateTimeException if the result exceeds the supported range
*/
public Year minusYears(long yearsToSubtract) {
return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
@@ -871,12 +871,12 @@
* The result will be negative if the end is before the start.
* The {@code Temporal} passed to this method is converted to a
* {@code Year} using {@link #from(TemporalAccessor)}.
- * For example, the period in decades between two year can be calculated
+ * For example, the amount in decades between two year can be calculated
* using {@code startYear.until(endYear, DECADES)}.
* <p>
* The calculation returns a whole number, representing the number of
* complete units between the two years.
- * For example, the period in decades between 2012 and 2031
+ * For example, the amount in decades between 2012 and 2031
* will only be one decade as it is one year short of two decades.
* <p>
* There are two equivalent ways of using this method.
@@ -948,7 +948,7 @@
* <p>
* The day-of-year value 366 is only valid in a leap year.
*
- * @param dayOfYear the day-of-year to use, not null
+ * @param dayOfYear the day-of-year to use, from 1 to 365-366
* @return the local date formed from this year and the specified date of year, not null
* @throws DateTimeException if the day of year is zero or less, 366 or greater or equal
* to 366 and this is not a leap year
@@ -1025,7 +1025,7 @@
}
/**
- * Is this year after the specified year.
+ * Checks if this year is after the specified year.
*
* @param other the other year to compare to, not null
* @return true if this is after the specified year
@@ -1035,7 +1035,7 @@
}
/**
- * Is this year before the specified year.
+ * Checks if this year is before the specified year.
*
* @param other the other year to compare to, not null
* @return true if this point is before the specified year
--- a/jdk/src/share/classes/java/time/YearMonth.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/YearMonth.java Mon May 12 09:37:50 2014 -0700
@@ -157,9 +157,8 @@
/**
* Obtains the current year-month from the system clock in the default time-zone.
* <p>
- * This will query the {@link java.time.Clock#systemDefaultZone() system clock} in the default
+ * This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current year-month.
- * The zone and offset will be set based on the time-zone in the clock.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
@@ -173,7 +172,7 @@
/**
* Obtains the current year-month from the system clock in the specified time-zone.
* <p>
- * This will query the {@link Clock#system(java.time.ZoneId) system clock} to obtain the current year-month.
+ * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current year-month.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
@@ -243,7 +242,7 @@
* chronology, or can be converted to a {@code LocalDate}.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
- * allowing it to be used in queries via method reference, {@code YearMonth::from}.
+ * allowing it to be used as a query via method reference, {@code YearMonth::from}.
*
* @param temporal the temporal object to convert, not null
* @return the year-month, not null
@@ -363,7 +362,7 @@
/**
* Checks if the specified unit is supported.
* <p>
- * This checks if the specified unit can be added to, or subtracted from, this date-time.
+ * This checks if the specified unit can be added to, or subtracted from, this year-month.
* If false, then calling the {@link #plus(long, TemporalUnit)} and
* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
* <p>
@@ -430,7 +429,7 @@
/**
* Gets the value of the specified field from this year-month as an {@code int}.
* <p>
- * This queries this year-month for the value for the specified field.
+ * This queries this year-month for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -462,7 +461,7 @@
/**
* Gets the value of the specified field from this year-month as a {@code long}.
* <p>
- * This queries this year-month for the value for the specified field.
+ * This queries this year-month for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
@@ -819,7 +818,7 @@
}
/**
- * Returns a copy of this year-month with the specified period in years added.
+ * Returns a copy of this {@code YearMonth} with the specified number of years added.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -836,7 +835,7 @@
}
/**
- * Returns a copy of this year-month with the specified period in months added.
+ * Returns a copy of this {@code YearMonth} with the specified number of months added.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -906,7 +905,7 @@
}
/**
- * Returns a copy of this year-month with the specified period in years subtracted.
+ * Returns a copy of this {@code YearMonth} with the specified number of years subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -919,7 +918,7 @@
}
/**
- * Returns a copy of this year-month with the specified period in months subtracted.
+ * Returns a copy of this {@code YearMonth} with the specified number of months subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
@@ -1004,12 +1003,12 @@
* The result will be negative if the end is before the start.
* The {@code Temporal} passed to this method is converted to a
* {@code YearMonth} using {@link #from(TemporalAccessor)}.
- * For example, the period in years between two year-months can be calculated
+ * For example, the amount in years between two year-months can be calculated
* using {@code startYearMonth.until(endYearMonth, YEARS)}.
* <p>
* The calculation returns a whole number, representing the number of
* complete units between the two year-months.
- * For example, the period in decades between 2012-06 and 2032-05
+ * For example, the amount in decades between 2012-06 and 2032-05
* will only be one decade as it is one month short of two decades.
* <p>
* There are two equivalent ways of using this method.
@@ -1134,7 +1133,7 @@
}
/**
- * Is this year-month after the specified year-month.
+ * Checks if this year-month is after the specified year-month.
*
* @param other the other year-month to compare to, not null
* @return true if this is after the specified year-month
@@ -1144,7 +1143,7 @@
}
/**
- * Is this year-month before the specified year-month.
+ * Checks if this year-month is before the specified year-month.
*
* @param other the other year-month to compare to, not null
* @return true if this point is before the specified year-month
--- a/jdk/src/share/classes/java/time/ZoneId.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/ZoneId.java Mon May 12 09:37:50 2014 -0700
@@ -453,7 +453,7 @@
* zones over offset-based zones using {@link TemporalQueries#zone()}.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
- * allowing it to be used in queries via method reference, {@code ZoneId::from}.
+ * allowing it to be used as a query via method reference, {@code ZoneId::from}.
*
* @param temporal the temporal object to convert, not null
* @return the zone ID, not null
--- a/jdk/src/share/classes/java/time/ZoneOffset.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/ZoneOffset.java Mon May 12 09:37:50 2014 -0700
@@ -89,7 +89,7 @@
/**
* A time-zone offset from Greenwich/UTC, such as {@code +02:00}.
* <p>
- * A time-zone offset is the period of time that a time-zone differs from Greenwich/UTC.
+ * A time-zone offset is the amount of time that a time-zone differs from Greenwich/UTC.
* This is usually a fixed number of hours and minutes.
* <p>
* Different parts of the world have different time-zone offsets.
@@ -334,7 +334,7 @@
* on extracting the {@link ChronoField#OFFSET_SECONDS OFFSET_SECONDS} field.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
- * allowing it to be used in queries via method reference, {@code ZoneOffset::from}.
+ * allowing it to be used as a query via method reference, {@code ZoneOffset::from}.
*
* @param temporal the temporal object to convert, not null
* @return the zone-offset, not null
@@ -564,7 +564,7 @@
/**
* Gets the value of the specified field from this offset as an {@code int}.
* <p>
- * This queries this offset for the value for the specified field.
+ * This queries this offset for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -599,7 +599,7 @@
/**
* Gets the value of the specified field from this offset as a {@code long}.
* <p>
- * This queries this offset for the value for the specified field.
+ * This queries this offset for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
--- a/jdk/src/share/classes/java/time/ZonedDateTime.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/ZonedDateTime.java Mon May 12 09:37:50 2014 -0700
@@ -418,7 +418,7 @@
* <p>
* Converting an instant to a zoned date-time is simple as there is only one valid
* offset for each instant. If the valid offset is different to the offset specified,
- * the the date-time and offset of the zoned date-time will differ from those specified.
+ * then the date-time and offset of the zoned date-time will differ from those specified.
* <p>
* If the {@code ZoneId} to be used is a {@code ZoneOffset}, this method is equivalent
* to {@link #of(LocalDateTime, ZoneId)}.
@@ -469,6 +469,7 @@
* @param offset the zone offset, not null
* @param zone the time-zone, not null
* @return the zoned date-time, not null
+ * @throws DateTimeException if the combination of arguments is invalid
*/
public static ZonedDateTime ofStrict(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone) {
Objects.requireNonNull(localDateTime, "localDateTime");
@@ -538,7 +539,7 @@
* those fields that are equivalent to the relevant objects.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
- * allowing it to be used in queries via method reference, {@code ZonedDateTime::from}.
+ * allowing it to be used as a query via method reference, {@code ZonedDateTime::from}.
*
* @param temporal the temporal object to convert, not null
* @return the zoned date-time, not null
@@ -782,7 +783,7 @@
/**
* Gets the value of the specified field from this date-time as an {@code int}.
* <p>
- * This queries this date-time for the value for the specified field.
+ * This queries this date-time for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -791,7 +792,7 @@
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this date-time, except {@code NANO_OF_DAY}, {@code MICRO_OF_DAY},
* {@code EPOCH_DAY}, {@code PROLEPTIC_MONTH} and {@code INSTANT_SECONDS} which are too
- * large to fit in an {@code int} and throw a {@code DateTimeException}.
+ * large to fit in an {@code int} and throw a {@code UnsupportedTemporalTypeException}.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
@@ -824,7 +825,7 @@
/**
* Gets the value of the specified field from this date-time as a {@code long}.
* <p>
- * This queries this date-time for the value for the specified field.
+ * This queries this date-time for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
@@ -1182,7 +1183,8 @@
* <p>
* A simple adjuster might simply set the one of the fields, such as the year field.
* A more complex adjuster might set the date to the last day of the month.
- * A selection of common adjustments is provided in {@link TemporalAdjuster}.
+ * A selection of common adjustments is provided in
+ * {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.
* These include finding the "last day of the month" and "next Wednesday".
* Key date-time classes also implement the {@code TemporalAdjuster} interface,
* such as {@link Month} and {@link java.time.MonthDay MonthDay}.
@@ -1192,7 +1194,7 @@
* For example this code returns a date on the last day of July:
* <pre>
* import static java.time.Month.*;
- * import static java.time.temporal.Adjusters.*;
+ * import static java.time.temporal.TemporalAdjusters.*;
*
* result = zonedDateTime.with(JULY).with(lastDayOfMonth());
* </pre>
@@ -1313,7 +1315,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code ZonedDateTime} with the year value altered.
+ * Returns a copy of this {@code ZonedDateTime} with the year altered.
* <p>
* This operates on the local time-line,
* {@link LocalDateTime#withYear(int) changing the year} of the local date-time.
@@ -1335,7 +1337,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the month-of-year value altered.
+ * Returns a copy of this {@code ZonedDateTime} with the month-of-year altered.
* <p>
* This operates on the local time-line,
* {@link LocalDateTime#withMonth(int) changing the month} of the local date-time.
@@ -1357,7 +1359,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the day-of-month value altered.
+ * Returns a copy of this {@code ZonedDateTime} with the day-of-month altered.
* <p>
* This operates on the local time-line,
* {@link LocalDateTime#withDayOfMonth(int) changing the day-of-month} of the local date-time.
@@ -1404,7 +1406,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code ZonedDateTime} with the hour-of-day value altered.
+ * Returns a copy of this {@code ZonedDateTime} with the hour-of-day altered.
* <p>
* This operates on the local time-line,
* {@linkplain LocalDateTime#withHour(int) changing the time} of the local date-time.
@@ -1426,7 +1428,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the minute-of-hour value altered.
+ * Returns a copy of this {@code ZonedDateTime} with the minute-of-hour altered.
* <p>
* This operates on the local time-line,
* {@linkplain LocalDateTime#withMinute(int) changing the time} of the local date-time.
@@ -1448,7 +1450,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the second-of-minute value altered.
+ * Returns a copy of this {@code ZonedDateTime} with the second-of-minute altered.
* <p>
* This operates on the local time-line,
* {@linkplain LocalDateTime#withSecond(int) changing the time} of the local date-time.
@@ -1470,7 +1472,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the nano-of-second value altered.
+ * Returns a copy of this {@code ZonedDateTime} with the nano-of-second altered.
* <p>
* This operates on the local time-line,
* {@linkplain LocalDateTime#withNano(int) changing the time} of the local date-time.
@@ -1506,7 +1508,7 @@
* {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.
* <p>
* This operates on the local time-line,
- * {@link LocalDateTime#truncatedTo(java.time.temporal.TemporalUnit) truncating}
+ * {@link LocalDateTime#truncatedTo(TemporalUnit) truncating}
* the underlying local date-time. This is then converted back to a
* {@code ZonedDateTime}, using the zone ID to obtain the offset.
* <p>
@@ -1607,7 +1609,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in years added.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of years added.
* <p>
* This operates on the local time-line,
* {@link LocalDateTime#plusYears(long) adding years} to the local date-time.
@@ -1629,7 +1631,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in months added.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of months added.
* <p>
* This operates on the local time-line,
* {@link LocalDateTime#plusMonths(long) adding months} to the local date-time.
@@ -1651,7 +1653,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in weeks added.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of weeks added.
* <p>
* This operates on the local time-line,
* {@link LocalDateTime#plusWeeks(long) adding weeks} to the local date-time.
@@ -1673,7 +1675,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in days added.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of days added.
* <p>
* This operates on the local time-line,
* {@link LocalDateTime#plusDays(long) adding days} to the local date-time.
@@ -1696,7 +1698,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in hours added.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of hours added.
* <p>
* This operates on the instant time-line, such that adding one hour will
* always be a duration of one hour later.
@@ -1724,7 +1726,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in minutes added.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of minutes added.
* <p>
* This operates on the instant time-line, such that adding one minute will
* always be a duration of one minute later.
@@ -1742,7 +1744,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in seconds added.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of seconds added.
* <p>
* This operates on the instant time-line, such that adding one second will
* always be a duration of one second later.
@@ -1760,7 +1762,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in nanoseconds added.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of nanoseconds added.
* <p>
* This operates on the instant time-line, such that adding one nano will
* always be a duration of one nano later.
@@ -1848,7 +1850,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in years subtracted.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of years subtracted.
* <p>
* This operates on the local time-line,
* {@link LocalDateTime#minusYears(long) subtracting years} to the local date-time.
@@ -1870,7 +1872,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in months subtracted.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of months subtracted.
* <p>
* This operates on the local time-line,
* {@link LocalDateTime#minusMonths(long) subtracting months} to the local date-time.
@@ -1892,7 +1894,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in weeks subtracted.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of weeks subtracted.
* <p>
* This operates on the local time-line,
* {@link LocalDateTime#minusWeeks(long) subtracting weeks} to the local date-time.
@@ -1914,7 +1916,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in days subtracted.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of days subtracted.
* <p>
* This operates on the local time-line,
* {@link LocalDateTime#minusDays(long) subtracting days} to the local date-time.
@@ -1937,7 +1939,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in hours subtracted.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of hours subtracted.
* <p>
* This operates on the instant time-line, such that subtracting one hour will
* always be a duration of one hour earlier.
@@ -1965,7 +1967,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in minutes subtracted.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of minutes subtracted.
* <p>
* This operates on the instant time-line, such that subtracting one minute will
* always be a duration of one minute earlier.
@@ -1983,7 +1985,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in seconds subtracted.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of seconds subtracted.
* <p>
* This operates on the instant time-line, such that subtracting one second will
* always be a duration of one second earlier.
@@ -2001,7 +2003,7 @@
}
/**
- * Returns a copy of this {@code ZonedDateTime} with the specified period in nanoseconds subtracted.
+ * Returns a copy of this {@code ZonedDateTime} with the specified number of nanoseconds subtracted.
* <p>
* This operates on the instant time-line, such that subtracting one nano will
* always be a duration of one nano earlier.
@@ -2028,7 +2030,7 @@
* what the result of this method will be.
* <p>
* The result of this method is obtained by invoking the
- * {@link java.time.temporal.TemporalQuery#queryFrom(TemporalAccessor)} method on the
+ * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
* specified query passing {@code this} as the argument.
*
* @param <R> the type of the result
@@ -2049,7 +2051,7 @@
* objects in terms of a single {@code TemporalUnit}.
* The start and end points are {@code this} and the specified date-time.
* The result will be negative if the end is before the start.
- * For example, the period in days between two date-times can be calculated
+ * For example, the amount in days between two date-times can be calculated
* using {@code startDateTime.until(endDateTime, DAYS)}.
* <p>
* The {@code Temporal} passed to this method is converted to a
@@ -2059,7 +2061,7 @@
* <p>
* The calculation returns a whole number, representing the number of
* complete units between the two date-times.
- * For example, the period in months between 2012-06-15T00:00Z and 2012-08-14T23:59Z
+ * For example, the amount in months between 2012-06-15T00:00Z and 2012-08-14T23:59Z
* will only be one month as it is one minute short of two months.
* <p>
* There are two equivalent ways of using this method.
--- a/jdk/src/share/classes/java/time/chrono/ChronoLocalDate.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/chrono/ChronoLocalDate.java Mon May 12 09:37:50 2014 -0700
@@ -249,8 +249,8 @@
* This allows dates in different calendar systems to be compared based
* on the position of the date on the local time-line.
* The underlying comparison is equivalent to comparing the epoch-day.
+ *
* @return a comparator that compares in time-line order ignoring the chronology
- *
* @see #isAfter
* @see #isBefore
* @see #isEqual
--- a/jdk/src/share/classes/java/time/chrono/ChronoLocalDateImpl.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/chrono/ChronoLocalDateImpl.java Mon May 12 09:37:50 2014 -0700
@@ -227,7 +227,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this date with the specified period in years added.
+ * Returns a copy of this date with the specified number of years added.
* <p>
* This adds the specified period in years to the date.
* In some cases, adding years can cause the resulting date to become invalid.
@@ -243,7 +243,7 @@
abstract D plusYears(long yearsToAdd);
/**
- * Returns a copy of this date with the specified period in months added.
+ * Returns a copy of this date with the specified number of months added.
* <p>
* This adds the specified period in months to the date.
* In some cases, adding months can cause the resulting date to become invalid.
@@ -259,7 +259,7 @@
abstract D plusMonths(long monthsToAdd);
/**
- * Returns a copy of this date with the specified period in weeks added.
+ * Returns a copy of this date with the specified number of weeks added.
* <p>
* This adds the specified period in weeks to the date.
* In some cases, adding weeks can cause the resulting date to become invalid.
@@ -292,7 +292,7 @@
//-----------------------------------------------------------------------
/**
- * Returns a copy of this date with the specified period in years subtracted.
+ * Returns a copy of this date with the specified number of years subtracted.
* <p>
* This subtracts the specified period in years to the date.
* In some cases, subtracting years can cause the resulting date to become invalid.
@@ -313,7 +313,7 @@
}
/**
- * Returns a copy of this date with the specified period in months subtracted.
+ * Returns a copy of this date with the specified number of months subtracted.
* <p>
* This subtracts the specified period in months to the date.
* In some cases, subtracting months can cause the resulting date to become invalid.
@@ -334,7 +334,7 @@
}
/**
- * Returns a copy of this date with the specified period in weeks subtracted.
+ * Returns a copy of this date with the specified number of weeks subtracted.
* <p>
* This subtracts the specified period in weeks to the date.
* In some cases, subtracting weeks can cause the resulting date to become invalid.
--- a/jdk/src/share/classes/java/time/chrono/ChronoLocalDateTime.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/chrono/ChronoLocalDateTime.java Mon May 12 09:37:50 2014 -0700
@@ -131,7 +131,6 @@
* The underlying comparison is equivalent to comparing the epoch-day and nano-of-day.
*
* @return a comparator that compares in time-line order ignoring the chronology
- *
* @see #isAfter
* @see #isBefore
* @see #isEqual
@@ -323,7 +322,7 @@
* what the result of this method will be.
* <p>
* The result of this method is obtained by invoking the
- * {@link java.time.temporal.TemporalQuery#queryFrom(TemporalAccessor)} method on the
+ * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
* specified query passing {@code this} as the argument.
*
* @param <R> the type of the result
--- a/jdk/src/share/classes/java/time/chrono/ChronoZonedDateTime.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/chrono/ChronoZonedDateTime.java Mon May 12 09:37:50 2014 -0700
@@ -132,7 +132,6 @@
* The underlying comparison is equivalent to comparing the epoch-second and nano-of-second.
*
* @return a comparator that compares in time-line order ignoring the chronology
- *
* @see #isAfter
* @see #isBefore
* @see #isEqual
@@ -292,7 +291,7 @@
* <p>
* This instance is immutable and unaffected by this method call.
*
- * @return a {@code ZoneChronoDateTime} based on this date-time with the earlier offset, not null
+ * @return a {@code ChronoZonedDateTime} based on this date-time with the earlier offset, not null
* @throws DateTimeException if no rules can be found for the zone
* @throws DateTimeException if no rules are valid for this date-time
*/
@@ -319,7 +318,7 @@
ChronoZonedDateTime<D> withLaterOffsetAtOverlap();
/**
- * Returns a copy of this ZonedDateTime with a different time-zone,
+ * Returns a copy of this date-time with a different time-zone,
* retaining the local date-time if possible.
* <p>
* This method changes the time-zone and retains the local date-time.
@@ -470,7 +469,7 @@
* what the result of this method will be.
* <p>
* The result of this method is obtained by invoking the
- * {@link java.time.temporal.TemporalQuery#queryFrom(TemporalAccessor)} method on the
+ * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
* specified query passing {@code this} as the argument.
*
* @param <R> the type of the result
--- a/jdk/src/share/classes/java/time/chrono/Chronology.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/chrono/Chronology.java Mon May 12 09:37:50 2014 -0700
@@ -132,8 +132,9 @@
* The set of available chronologies can be extended by applications.
* Adding a new calendar system requires the writing of an implementation of
* {@code Chronology}, {@code ChronoLocalDate} and {@code Era}.
- * The majority of the logic specific to the calendar system will be in
- * {@code ChronoLocalDate}. The {@code Chronology} subclass acts as a factory.
+ * The majority of the logic specific to the calendar system will be in the
+ * {@code ChronoLocalDate} implementation.
+ * The {@code Chronology} implementation acts as a factory.
* <p>
* To permit the discovery of additional chronologies, the {@link java.util.ServiceLoader ServiceLoader}
* is used. A file must be added to the {@code META-INF/services} directory with the
@@ -167,7 +168,7 @@
* If the specified temporal object does not have a chronology, {@link IsoChronology} is returned.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
- * allowing it to be used in queries via method reference, {@code Chronology::from}.
+ * allowing it to be used as a query via method reference, {@code Chronology::from}.
*
* @param temporal the temporal to convert, not null
* @return the chronology, not null
@@ -413,7 +414,7 @@
* The alternate clock may be introduced using {@link Clock dependency injection}.
*
* @implSpec
- * The default implementation invokes {@link #date(TemporalAccessor)} )}.
+ * The default implementation invokes {@link #date(TemporalAccessor)}.
*
* @param clock the clock to use, not null
* @return the current local date, not null
@@ -622,7 +623,7 @@
* The parameters control the style of the returned text and the locale.
*
* @implSpec
- * The default implementation behaves as the the formatter was used to
+ * The default implementation behaves as though the formatter was used to
* format the chronology textual name.
*
* @param style the style of the text required, not null
--- a/jdk/src/share/classes/java/time/chrono/Era.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/chrono/Era.java Mon May 12 09:37:50 2014 -0700
@@ -182,7 +182,7 @@
/**
* Gets the value of the specified field from this era as an {@code int}.
* <p>
- * This queries this era for the value for the specified field.
+ * This queries this era for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
@@ -215,7 +215,7 @@
/**
* Gets the value of the specified field from this era as a {@code long}.
* <p>
- * This queries this era for the value for the specified field.
+ * This queries this era for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
--- a/jdk/src/share/classes/java/time/chrono/HijrahChronology.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/chrono/HijrahChronology.java Mon May 12 09:37:50 2014 -0700
@@ -394,7 +394,7 @@
* Gets the ID of the chronology.
* <p>
* The ID uniquely identifies the {@code Chronology}. It can be used to
- * lookup the {@code Chronology} using {@link #of(String)}.
+ * lookup the {@code Chronology} using {@link Chronology#of(String)}.
*
* @return the chronology ID, non-null
* @see #getCalendarType()
@@ -409,7 +409,7 @@
* <p>
* The calendar type is an identifier defined by the
* <em>Unicode Locale Data Markup Language (LDML)</em> specification.
- * It can be used to lookup the {@code Chronology} using {@link #of(String)}.
+ * It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.
*
* @return the calendar system type; non-null if the calendar has
* a standard type, otherwise null
--- a/jdk/src/share/classes/java/time/chrono/IsoChronology.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/chrono/IsoChronology.java Mon May 12 09:37:50 2014 -0700
@@ -143,7 +143,7 @@
* Gets the ID of the chronology - 'ISO'.
* <p>
* The ID uniquely identifies the {@code Chronology}.
- * It can be used to lookup the {@code Chronology} using {@link #of(String)}.
+ * It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.
*
* @return the chronology ID - 'ISO'
* @see #getCalendarType()
@@ -158,7 +158,7 @@
* <p>
* The calendar type is an identifier defined by the
* <em>Unicode Locale Data Markup Language (LDML)</em> specification.
- * It can be used to lookup the {@code Chronology} using {@link #of(String)}.
+ * It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.
* It can also be used as part of a locale, accessible via
* {@link Locale#getUnicodeLocaleType(String)} with the key 'ca'.
*
--- a/jdk/src/share/classes/java/time/chrono/JapaneseChronology.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/chrono/JapaneseChronology.java Mon May 12 09:37:50 2014 -0700
@@ -150,7 +150,7 @@
* Gets the ID of the chronology - 'Japanese'.
* <p>
* The ID uniquely identifies the {@code Chronology}.
- * It can be used to lookup the {@code Chronology} using {@link #of(String)}.
+ * It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.
*
* @return the chronology ID - 'Japanese'
* @see #getCalendarType()
@@ -165,7 +165,7 @@
* <p>
* The calendar type is an identifier defined by the
* <em>Unicode Locale Data Markup Language (LDML)</em> specification.
- * It can be used to lookup the {@code Chronology} using {@link #of(String)}.
+ * It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.
* It can also be used as part of a locale, accessible via
* {@link Locale#getUnicodeLocaleType(String)} with the key 'ca'.
*
--- a/jdk/src/share/classes/java/time/chrono/MinguoChronology.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/chrono/MinguoChronology.java Mon May 12 09:37:50 2014 -0700
@@ -132,7 +132,7 @@
* Gets the ID of the chronology - 'Minguo'.
* <p>
* The ID uniquely identifies the {@code Chronology}.
- * It can be used to lookup the {@code Chronology} using {@link #of(String)}.
+ * It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.
*
* @return the chronology ID - 'Minguo'
* @see #getCalendarType()
@@ -147,7 +147,7 @@
* <p>
* The calendar type is an identifier defined by the
* <em>Unicode Locale Data Markup Language (LDML)</em> specification.
- * It can be used to lookup the {@code Chronology} using {@link #of(String)}.
+ * It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.
* It can also be used as part of a locale, accessible via
* {@link Locale#getUnicodeLocaleType(String)} with the key 'ca'.
*
--- a/jdk/src/share/classes/java/time/chrono/ThaiBuddhistChronology.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/chrono/ThaiBuddhistChronology.java Mon May 12 09:37:50 2014 -0700
@@ -168,7 +168,7 @@
* Gets the ID of the chronology - 'ThaiBuddhist'.
* <p>
* The ID uniquely identifies the {@code Chronology}.
- * It can be used to lookup the {@code Chronology} using {@link #of(String)}.
+ * It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.
*
* @return the chronology ID - 'ThaiBuddhist'
* @see #getCalendarType()
@@ -183,7 +183,7 @@
* <p>
* The calendar type is an identifier defined by the
* <em>Unicode Locale Data Markup Language (LDML)</em> specification.
- * It can be used to lookup the {@code Chronology} using {@link #of(String)}.
+ * It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.
* It can also be used as part of a locale, accessible via
* {@link Locale#getUnicodeLocaleType(String)} with the key 'ca'.
*
--- a/jdk/src/share/classes/java/time/format/DateTimeFormatter.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/format/DateTimeFormatter.java Mon May 12 09:37:50 2014 -0700
@@ -117,7 +117,7 @@
* {@code parse(CharSequence text, DateTimeFormatter formatter)}.
* <p>For example:
* <blockquote><pre>
- * String text = date.toString(formatter);
+ * String text = date.format(formatter);
* LocalDate date = LocalDate.parse(text, formatter);
* </pre></blockquote>
* <p>
@@ -266,7 +266,7 @@
* For example:
* <blockquote><pre>
* DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
- * String text = date.toString(formatter);
+ * String text = date.format(formatter);
* LocalDate date = LocalDate.parse(text, formatter);
* </pre></blockquote>
* <p>
@@ -1976,7 +1976,7 @@
* Errors are returned using the error index field of the {@code ParsePosition}
* instead of {@code DateTimeParseException}.
* The returned error index will be set to an index indicative of the error.
- * Callers must check for errors before using the context.
+ * Callers must check for errors before using the result.
* <p>
* If the formatter parses the same field more than once with different values,
* the result will be an error.
--- a/jdk/src/share/classes/java/time/format/DateTimeFormatterBuilder.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/format/DateTimeFormatterBuilder.java Mon May 12 09:37:50 2014 -0700
@@ -137,7 +137,6 @@
* <li>ChronologyText - the name of the chronology</li>
* <li>Literal - a text literal</li>
* <li>Nested and Optional - formats can be nested or made optional</li>
- * <li>Other - the printer and parser interfaces can be used to add user supplied formatting</li>
* </ul>
* In addition, any of the elements may be decorated by padding, either with spaces or any other character.
* <p>
@@ -194,8 +193,8 @@
* The locale and chronology are used to lookup the locale specific format
* for the requested dateStyle and/or timeStyle.
*
- * @param dateStyle the FormatStyle for the date
- * @param timeStyle the FormatStyle for the time
+ * @param dateStyle the FormatStyle for the date, null for time-only pattern
+ * @param timeStyle the FormatStyle for the time, null for date-only pattern
* @param chrono the Chronology, non-null
* @param locale the locale, non-null
* @return the locale and Chronology specific formatting pattern
@@ -747,9 +746,9 @@
* defines the connection between each value and the text:
* <pre>
* Map<Long, String> map = new HashMap<>();
- * map.put(1, "JNY");
- * map.put(2, "FBY");
- * map.put(3, "MCH");
+ * map.put(1L, "JNY");
+ * map.put(2L, "FBY");
+ * map.put(3L, "MCH");
* ...
* builder.appendText(MONTH_OF_YEAR, map);
* </pre>
@@ -841,7 +840,7 @@
* <p>
* The {@linkplain ResolverStyle resolver style} has no effect on instant parsing.
* The end-of-day time of '24:00' is handled as midnight at the start of the following day.
- * The leap-second time of '23:59:59' is handled to some degree, see
+ * The leap-second time of '23:59:60' is handled to some degree, see
* {@link DateTimeFormatter#parsedLeapSecond()} for full details.
* <p>
* An alternative to this method is to format/parse the instant as a single
@@ -864,7 +863,7 @@
* Appends the zone offset, such as '+01:00', to the formatter.
* <p>
* This appends an instruction to format/parse the offset ID to the builder.
- * This is equivalent to calling {@code appendOffset("HH:MM:ss", "Z")}.
+ * This is equivalent to calling {@code appendOffset("+HH:MM:ss", "Z")}.
*
* @return this, for chaining, not null
*/
@@ -1049,7 +1048,7 @@
* "GMT+01:30" -- ZoneOffset.of("+01:30")
* </pre>
* <p>
- * Note that this method is is identical to {@code appendZoneId()} except
+ * Note that this method is identical to {@code appendZoneId()} except
* in the mechanism used to obtain the zone.
* Note also that parsing accepts offsets, whereas formatting will never
* produce one.
@@ -1107,7 +1106,7 @@
* "GMT+01:30" -- ZoneOffset.of("GMT+01:30")
* </pre>
* <p>
- * Note that this method is is identical to {@code appendZoneId()} except
+ * Note that this method is identical to {@code appendZoneId()} except
* in the mechanism used to obtain the zone.
*
* @return this, for chaining, not null
@@ -1132,7 +1131,7 @@
* for the locale set in the {@link DateTimeFormatter}.
* If the temporal object being printed represents an instant, then the text
* will be the summer or winter time text as appropriate.
- * If the lookup for text does not find any suitable reuslt, then the
+ * If the lookup for text does not find any suitable result, then the
* {@link ZoneId#getId() ID} will be printed instead.
* If the zone cannot be obtained then an exception is thrown unless the
* section of the formatter is optional.
@@ -1168,7 +1167,7 @@
* for the locale set in the {@link DateTimeFormatter}.
* If the temporal object being printed represents an instant, then the text
* will be the summer or winter time text as appropriate.
- * If the lookup for text does not find any suitable reuslt, then the
+ * If the lookup for text does not find any suitable result, then the
* {@link ZoneId#getId() ID} will be printed instead.
* If the zone cannot be obtained then an exception is thrown unless the
* section of the formatter is optional.
@@ -1182,7 +1181,7 @@
* zone. This method also allows a set of preferred {@link ZoneId} to be
* specified for parsing. The matched preferred zone id will be used if the
* textural zone name being parsed is not unique.
- *
+ * <p>
* If the zone cannot be parsed then an exception is thrown unless the
* section of the formatter is optional.
*
@@ -1227,7 +1226,6 @@
* <p>
* The calendar system name will be output during a format.
* If the chronology cannot be obtained then an exception will be thrown.
- * The calendar system name is obtained from the Chronology.
*
* @param textStyle the text style to use, not null
* @return this, for chaining, not null
@@ -1453,7 +1451,7 @@
* LLLLL 5 appendText(ChronoField.MONTH_OF_YEAR, TextStyle.NARROW_STANDALONE)
*
* w 1 append special localized WeekFields element for numeric week-of-year
- * ww 1 append special localized WeekFields element for numeric week-of-year, zero-padded
+ * ww 2 append special localized WeekFields element for numeric week-of-year, zero-padded
* W 1 append special localized WeekFields element for numeric week-of-month
* d 1 appendValue(ChronoField.DAY_OF_MONTH)
* dd 2 appendValue(ChronoField.DAY_OF_MONTH, 2)
@@ -1880,7 +1878,6 @@
* <p>
* During parsing, the padding and decorated element are parsed.
* If parsing is lenient, then the pad width is treated as a maximum.
- * If parsing is case insensitive, then the pad character is matched ignoring case.
* The padding is parsed greedily. Thus, if the decorated element starts with
* the pad character, it will not be parsed.
*
--- a/jdk/src/share/classes/java/time/format/DecimalStyle.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/format/DecimalStyle.java Mon May 12 09:37:50 2014 -0700
@@ -62,7 +62,6 @@
package java.time.format;
import java.text.DecimalFormatSymbols;
-import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
@@ -138,7 +137,7 @@
* of(Locale.getDefault(Locale.Category.FORMAT))}.
*
* @see java.util.Locale.Category#FORMAT
- * @return the info, not null
+ * @return the decimal style, not null
*/
public static DecimalStyle ofDefaultLocale() {
return of(Locale.getDefault(Locale.Category.FORMAT));
@@ -150,7 +149,7 @@
* This method provides access to locale sensitive decimal style symbols.
*
* @param locale the locale, not null
- * @return the info, not null
+ * @return the decimal style, not null
*/
public static DecimalStyle of(Locale locale) {
Objects.requireNonNull(locale, "locale");
@@ -340,7 +339,7 @@
//-----------------------------------------------------------------------
/**
- * Checks if this DecimalStyle is equal another DecimalStyle.
+ * Checks if this DecimalStyle is equal to another DecimalStyle.
*
* @param obj the object to check, null returns false
* @return true if this is equal to the other date
--- a/jdk/src/share/classes/java/time/temporal/IsoFields.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/temporal/IsoFields.java Mon May 12 09:37:50 2014 -0700
@@ -638,7 +638,7 @@
//-----------------------------------------------------------------------
/**
- * Implementation of the period unit.
+ * Implementation of the unit.
*/
private static enum Unit implements TemporalUnit {
--- a/jdk/src/share/classes/java/time/temporal/Temporal.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/temporal/Temporal.java Mon May 12 09:37:50 2014 -0700
@@ -157,7 +157,8 @@
* This adjusts this date-time according to the rules of the specified adjuster.
* A simple adjuster might simply set the one of the fields, such as the year field.
* A more complex adjuster might set the date to the last day of the month.
- * A selection of common adjustments is provided in {@link TemporalAdjuster}.
+ * A selection of common adjustments is provided in
+ * {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.
* These include finding the "last day of the month" and "next Wednesday".
* The adjuster is responsible for handling special cases, such as the varying
* lengths of month and leap years.
@@ -287,7 +288,7 @@
* This provides equivalent, safe behavior for immutable and mutable implementations.
*
* @param amountToAdd the amount of the specified unit to add, may be negative
- * @param unit the unit of the period to add, not null
+ * @param unit the unit of the amount to add, not null
* @return an object of the same type with the specified period added, not null
* @throws DateTimeException if the unit cannot be added
* @throws UnsupportedTemporalTypeException if the unit is not supported
@@ -359,7 +360,7 @@
* </pre>
*
* @param amountToSubtract the amount of the specified unit to subtract, may be negative
- * @param unit the unit of the period to subtract, not null
+ * @param unit the unit of the amount to subtract, not null
* @return an object of the same type with the specified period subtracted, not null
* @throws DateTimeException if the unit cannot be subtracted
* @throws UnsupportedTemporalTypeException if the unit is not supported
@@ -378,12 +379,12 @@
* The start and end points are {@code this} and the specified temporal.
* The end point is converted to be of the same type as the start point if different.
* The result will be negative if the end is before the start.
- * For example, the period in hours between two temporal objects can be
+ * For example, the amount in hours between two temporal objects can be
* calculated using {@code startTime.until(endTime, HOURS)}.
* <p>
* The calculation returns a whole number, representing the number of
* complete units between the two temporals.
- * For example, the period in hours between the times 11:30 and 13:29
+ * For example, the amount in hours between the times 11:30 and 13:29
* will only be one hour as it is one minute short of two hours.
* <p>
* There are two equivalent ways of using this method.
--- a/jdk/src/share/classes/java/time/temporal/TemporalAccessor.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/temporal/TemporalAccessor.java Mon May 12 09:37:50 2014 -0700
@@ -180,7 +180,7 @@
/**
* Gets the value of the specified field as an {@code int}.
* <p>
- * This queries the date-time for the value for the specified field.
+ * This queries the date-time for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If the date-time cannot return the value, because the field is unsupported or for
* some other reason, an exception will be thrown.
@@ -229,7 +229,7 @@
/**
* Gets the value of the specified field as a {@code long}.
* <p>
- * This queries the date-time for the value for the specified field.
+ * This queries the date-time for the value of the specified field.
* The returned value may be outside the valid range of values for the field.
* If the date-time cannot return the value, because the field is unsupported or for
* some other reason, an exception will be thrown.
--- a/jdk/src/share/classes/java/time/temporal/TemporalField.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/temporal/TemporalField.java Mon May 12 09:37:50 2014 -0700
@@ -116,7 +116,7 @@
* For example, in the field 'MonthOfYear', the unit is 'Months'.
* See also {@link #getRangeUnit()}.
*
- * @return the period unit defining the base unit of the field, not null
+ * @return the unit defining the base unit of the field, not null
*/
TemporalUnit getBaseUnit();
@@ -130,7 +130,7 @@
* The range is never null. For example, the 'Year' field is shorthand for
* 'YearOfForever'. It therefore has a unit of 'Years' and a range of 'Forever'.
*
- * @return the period unit defining the range of the field, not null
+ * @return the unit defining the range of the field, not null
*/
TemporalUnit getRangeUnit();
@@ -179,7 +179,7 @@
* Checks if this field is supported by the temporal object.
* <p>
* This determines whether the temporal accessor supports this field.
- * If this returns false, the the temporal cannot be queried for this field.
+ * If this returns false, then the temporal cannot be queried for this field.
* <p>
* There are two equivalent ways of using this method.
* The first is to invoke this method directly.
--- a/jdk/src/share/classes/java/time/temporal/TemporalUnit.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/temporal/TemporalUnit.java Mon May 12 09:37:50 2014 -0700
@@ -221,7 +221,7 @@
* @param temporal the temporal object to adjust, not null
* @param amount the amount of this unit to add, positive or negative
* @return the adjusted temporal object, not null
- * @throws DateTimeException if the period cannot be added
+ * @throws DateTimeException if the amount cannot be added
* @throws UnsupportedTemporalTypeException if the unit is not supported by the temporal
*/
<R extends Temporal> R addTo(R temporal, long amount);
--- a/jdk/src/share/classes/java/time/zone/ZoneOffsetTransition.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/time/zone/ZoneOffsetTransition.java Mon May 12 09:37:50 2014 -0700
@@ -83,7 +83,7 @@
* The discontinuity is normally a gap in spring and an overlap in autumn.
* {@code ZoneOffsetTransition} models the transition between the two offsets.
* <p>
- * Gaps occur where there are local date-times that simply do not not exist.
+ * Gaps occur where there are local date-times that simply do not exist.
* An example would be when the offset changes from {@code +03:00} to {@code +04:00}.
* This might be described as 'the clocks will move forward one hour tonight at 1am'.
* <p>
@@ -334,7 +334,7 @@
/**
* Does this transition represent a gap in the local time-line.
* <p>
- * Gaps occur where there are local date-times that simply do not not exist.
+ * Gaps occur where there are local date-times that simply do not exist.
* An example would be when the offset changes from {@code +01:00} to {@code +02:00}.
* This might be described as 'the clocks will move forward one hour tonight at 1am'.
*
--- a/jdk/src/share/classes/java/util/BitSet.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/util/BitSet.java Mon May 12 09:37:50 2014 -0700
@@ -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
@@ -696,6 +696,9 @@
* <pre> {@code
* for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
* // operate on index i here
+ * if (i == Integer.MAX_VALUE) {
+ * break; // or (i+1) would overflow
+ * }
* }}</pre>
*
* @param fromIndex the index to start checking from (inclusive)
@@ -1186,10 +1189,12 @@
int i = nextSetBit(0);
if (i != -1) {
b.append(i);
- for (i = nextSetBit(i+1); i >= 0; i = nextSetBit(i+1)) {
+ while (true) {
+ if (++i < 0) break;
+ if ((i = nextSetBit(i)) < 0) break;
int endOfRun = nextClearBit(i);
do { b.append(", ").append(i); }
- while (++i < endOfRun);
+ while (++i != endOfRun);
}
}
--- a/jdk/src/share/classes/java/util/Hashtable.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/util/Hashtable.java Mon May 12 09:37:50 2014 -0700
@@ -26,7 +26,6 @@
package java.util;
import java.io.*;
-import java.util.concurrent.ThreadLocalRandom;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.BiFunction;
@@ -92,8 +91,10 @@
* ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behavior at an undetermined time in the future.
- * The Enumerations returned by Hashtable's keys and elements methods are
- * <em>not</em> fail-fast.
+ * The Enumerations returned by Hashtable's {@link #keys keys} and
+ * {@link #elements elements} methods are <em>not</em> fail-fast; if the
+ * Hashtable is structurally modified at any time after the enumeration is
+ * created then the results of enumerating are undefined.
*
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
@@ -115,6 +116,9 @@
* to use {@link java.util.concurrent.ConcurrentHashMap} in place of
* {@code Hashtable}.
*
+ * @param <K> the type of keys maintained by this map
+ * @param <V> the type of mapped values
+ *
* @author Arthur van Hoff
* @author Josh Bloch
* @author Neal Gafter
@@ -246,6 +250,9 @@
/**
* Returns an enumeration of the keys in this hashtable.
+ * Use the Enumeration methods on the returned object to fetch the keys
+ * sequentially. If the hashtable is structurally modified while enumerating
+ * over the keys then the results of enumerating are undefined.
*
* @return an enumeration of the keys in this hashtable.
* @see Enumeration
@@ -260,7 +267,8 @@
/**
* Returns an enumeration of the values in this hashtable.
* Use the Enumeration methods on the returned object to fetch the elements
- * sequentially.
+ * sequentially. If the hashtable is structurally modified while enumerating
+ * over the values then the results of enumerating are undefined.
*
* @return an enumeration of the values in this hashtable.
* @see java.util.Enumeration
@@ -417,8 +425,6 @@
}
private void addEntry(int hash, K key, V value, int index) {
- modCount++;
-
Entry<?,?> tab[] = table;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
@@ -434,6 +440,7 @@
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
+ modCount++;
}
/**
@@ -494,12 +501,12 @@
Entry<K,V> e = (Entry<K,V>)tab[index];
for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
- modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
+ modCount++;
count--;
V oldValue = e.value;
e.value = null;
@@ -528,9 +535,9 @@
*/
public synchronized void clear() {
Entry<?,?> tab[] = table;
- modCount++;
for (int index = tab.length; --index >= 0; )
tab[index] = null;
+ modCount++;
count = 0;
}
@@ -719,14 +726,14 @@
Entry<K,V> e = (Entry<K,V>)tab[index];
for(Entry<K,V> prev = null; e != null; prev = e, e = e.next) {
if (e.hash==hash && e.equals(entry)) {
- modCount++;
if (prev != null)
prev.next = e.next;
else
tab[index] = e.next;
+ e.value = null; // clear for gc.
+ modCount++;
count--;
- e.value = null;
return true;
}
}
@@ -939,14 +946,14 @@
Entry<K,V> e = (Entry<K,V>)tab[index];
for (Entry<K,V> prev = null; e != null; prev = e, e = e.next) {
if ((e.hash == hash) && e.key.equals(key) && e.value.equals(value)) {
- modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
+ e.value = null; // clear for gc
+ modCount++;
count--;
- e.value = null;
return true;
}
}
@@ -1030,12 +1037,12 @@
if (e.hash == hash && e.key.equals(key)) {
V newValue = remappingFunction.apply(key, e.value);
if (newValue == null) {
- modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
+ modCount++;
count--;
} else {
e.value = newValue;
@@ -1059,12 +1066,12 @@
if (e.hash == hash && Objects.equals(e.key, key)) {
V newValue = remappingFunction.apply(key, e.value);
if (newValue == null) {
- modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
+ modCount++;
count--;
} else {
e.value = newValue;
@@ -1094,12 +1101,12 @@
if (e.hash == hash && e.key.equals(key)) {
V newValue = remappingFunction.apply(e.value, value);
if (newValue == null) {
- modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
+ modCount++;
count--;
} else {
e.value = newValue;
@@ -1298,24 +1305,24 @@
* by passing an Enumeration.
*/
private class Enumerator<T> implements Enumeration<T>, Iterator<T> {
- Entry<?,?>[] table = Hashtable.this.table;
+ final Entry<?,?>[] table = Hashtable.this.table;
int index = table.length;
Entry<?,?> entry;
Entry<?,?> lastReturned;
- int type;
+ final int type;
/**
* Indicates whether this Enumerator is serving as an Iterator
* or an Enumeration. (true -> Iterator).
*/
- boolean iterator;
+ final boolean iterator;
/**
* The modCount value that the iterator believes that the backing
* Hashtable should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
- protected int expectedModCount = modCount;
+ protected int expectedModCount = Hashtable.this.modCount;
Enumerator(int type, boolean iterator) {
this.type = type;
@@ -1360,7 +1367,7 @@
}
public T next() {
- if (modCount != expectedModCount)
+ if (Hashtable.this.modCount != expectedModCount)
throw new ConcurrentModificationException();
return nextElement();
}
@@ -1381,14 +1388,14 @@
Entry<K,V> e = (Entry<K,V>)tab[index];
for(Entry<K,V> prev = null; e != null; prev = e, e = e.next) {
if (e == lastReturned) {
- modCount++;
- expectedModCount++;
if (prev == null)
tab[index] = e.next;
else
prev.next = e.next;
- count--;
+ expectedModCount++;
lastReturned = null;
+ Hashtable.this.modCount++;
+ Hashtable.this.count--;
return;
}
}
--- a/jdk/src/share/classes/java/util/Locale.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/util/Locale.java Mon May 12 09:37:50 2014 -0700
@@ -2904,8 +2904,8 @@
for (int i = 1; i < subtags.length; i++) {
if (isSubtagIllFormed(subtags[i], false)) {
isIllFormed = true;
+ break;
}
- break;
}
}
if (isIllFormed) {
--- a/jdk/src/share/classes/java/util/Vector.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/util/Vector.java Mon May 12 09:37:50 2014 -0700
@@ -56,7 +56,9 @@
* concurrent modification, the iterator fails quickly and cleanly, rather
* than risking arbitrary, non-deterministic behavior at an undetermined
* time in the future. The {@link Enumeration Enumerations} returned by
- * the {@link #elements() elements} method are <em>not</em> fail-fast.
+ * the {@link #elements() elements} method are <em>not</em> fail-fast; if the
+ * Vector is structurally modified at any time after the enumeration is
+ * created then the results of enumerating are undefined.
*
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
@@ -74,6 +76,8 @@
* implementation is not needed, it is recommended to use {@link
* ArrayList} in place of {@code Vector}.
*
+ * @param <E> Type of component elements
+ *
* @author Lee Boynton
* @author Jonathan Payne
* @see Collection
@@ -330,7 +334,9 @@
* Returns an enumeration of the components of this vector. The
* returned {@code Enumeration} object will generate all items in
* this vector. The first item generated is the item at index {@code 0},
- * then the item at index {@code 1}, and so on.
+ * then the item at index {@code 1}, and so on. If the vector is
+ * structurally modified while enumerating over the elements then the
+ * results of enumerating are undefined.
*
* @return an enumeration of the components of this vector
* @see Iterator
@@ -553,7 +559,6 @@
* ({@code index < 0 || index >= size()})
*/
public synchronized void removeElementAt(int index) {
- modCount++;
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
@@ -565,6 +570,7 @@
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
+ modCount++;
elementCount--;
elementData[elementCount] = null; /* to let gc do its work */
}
@@ -593,7 +599,6 @@
* ({@code index < 0 || index > size()})
*/
public synchronized void insertElementAt(E obj, int index) {
- modCount++;
if (index > elementCount) {
throw new ArrayIndexOutOfBoundsException(index
+ " > " + elementCount);
@@ -601,6 +606,7 @@
ensureCapacityHelper(elementCount + 1);
System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
elementData[index] = obj;
+ modCount++;
elementCount++;
}
@@ -616,8 +622,8 @@
* @param obj the component to be added
*/
public synchronized void addElement(E obj) {
+ ensureCapacityHelper(elementCount + 1);
modCount++;
- ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
@@ -653,11 +659,11 @@
* method (which is part of the {@link List} interface).
*/
public synchronized void removeAllElements() {
- modCount++;
// Let gc do its work
for (int i = 0; i < elementCount; i++)
elementData[i] = null;
+ modCount++;
elementCount = 0;
}
@@ -705,12 +711,15 @@
* of the Vector <em>only</em> if the caller knows that the Vector
* does not contain any null elements.)
*
+ * @param <T> type of array elements. The same type as {@code <E>} or a
+ * supertype of {@code <E>}.
* @param a the array into which the elements of the Vector are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the Vector
- * @throws ArrayStoreException if the runtime type of a is not a supertype
- * of the runtime type of every element in this Vector
+ * @throws ArrayStoreException if the runtime type of a, {@code <T>}, is not
+ * a supertype of the runtime type, {@code <E>}, of every element in this
+ * Vector
* @throws NullPointerException if the given array is null
* @since 1.2
*/
@@ -778,8 +787,8 @@
* @since 1.2
*/
public synchronized boolean add(E e) {
+ ensureCapacityHelper(elementCount + 1);
modCount++;
- ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
@@ -879,14 +888,18 @@
* @throws NullPointerException if the specified collection is null
* @since 1.2
*/
- public synchronized boolean addAll(Collection<? extends E> c) {
- modCount++;
+ public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
- ensureCapacityHelper(elementCount + numNew);
- System.arraycopy(a, 0, elementData, elementCount, numNew);
- elementCount += numNew;
- return numNew != 0;
+ if (numNew > 0) {
+ synchronized (this) {
+ ensureCapacityHelper(elementCount + numNew);
+ System.arraycopy(a, 0, elementData, elementCount, numNew);
+ modCount++;
+ elementCount += numNew;
+ }
+ }
+ return numNew > 0;
}
/**
@@ -951,22 +964,25 @@
* @since 1.2
*/
public synchronized boolean addAll(int index, Collection<? extends E> c) {
- modCount++;
if (index < 0 || index > elementCount)
throw new ArrayIndexOutOfBoundsException(index);
Object[] a = c.toArray();
int numNew = a.length;
- ensureCapacityHelper(elementCount + numNew);
+
+ if (numNew > 0) {
+ ensureCapacityHelper(elementCount + numNew);
- int numMoved = elementCount - index;
- if (numMoved > 0)
- System.arraycopy(elementData, index, elementData, index + numNew,
- numMoved);
+ int numMoved = elementCount - index;
+ if (numMoved > 0)
+ System.arraycopy(elementData, index, elementData,
+ index + numNew, numMoved);
- System.arraycopy(a, 0, elementData, index, numNew);
- elementCount += numNew;
- return numNew != 0;
+ System.arraycopy(a, 0, elementData, index, numNew);
+ elementCount += numNew;
+ modCount++;
+ }
+ return numNew > 0;
}
/**
@@ -1047,12 +1063,12 @@
* (If {@code toIndex==fromIndex}, this operation has no effect.)
*/
protected synchronized void removeRange(int fromIndex, int toIndex) {
- modCount++;
int numMoved = elementCount - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// Let gc do its work
+ modCount++;
int newElementCount = elementCount - (toIndex-fromIndex);
while (elementCount != newElementCount)
elementData[--elementCount] = null;
@@ -1420,7 +1436,7 @@
}
public long estimateSize() {
- return (long) (getFence() - index);
+ return getFence() - index;
}
public int characteristics() {
--- a/jdk/src/share/classes/java/util/stream/SortedOps.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/java/util/stream/SortedOps.java Mon May 12 09:37:50 2014 -0700
@@ -279,16 +279,60 @@
}
/**
+ * Abstract {@link Sink} for implementing sort on reference streams.
+ *
+ * <p>
+ * Note: documentation below applies to reference and all primitive sinks.
+ * <p>
+ * Sorting sinks first accept all elements, buffering then into an array
+ * or a re-sizable data structure, if the size of the pipeline is known or
+ * unknown respectively. At the end of the sink protocol those elements are
+ * sorted and then pushed downstream.
+ * This class records if {@link #cancellationRequested} is called. If so it
+ * can be inferred that the source pushing source elements into the pipeline
+ * knows that the pipeline is short-circuiting. In such cases sub-classes
+ * pushing elements downstream will preserve the short-circuiting protocol
+ * by calling {@code downstream.cancellationRequested()} and checking the
+ * result is {@code false} before an element is pushed.
+ * <p>
+ * Note that the above behaviour is an optimization for sorting with
+ * sequential streams. It is not an error that more elements, than strictly
+ * required to produce a result, may flow through the pipeline. This can
+ * occur, in general (not restricted to just sorting), for short-circuiting
+ * parallel pipelines.
+ */
+ private static abstract class AbstractRefSortingSink<T> extends Sink.ChainedReference<T, T> {
+ protected final Comparator<? super T> comparator;
+ // @@@ could be a lazy final value, if/when support is added
+ protected boolean cancellationWasRequested;
+
+ AbstractRefSortingSink(Sink<? super T> downstream, Comparator<? super T> comparator) {
+ super(downstream);
+ this.comparator = comparator;
+ }
+
+ /**
+ * Records is cancellation is requested so short-circuiting behaviour
+ * can be preserved when the sorted elements are pushed downstream.
+ *
+ * @return false, as this sink never short-circuits.
+ */
+ @Override
+ public final boolean cancellationRequested() {
+ cancellationWasRequested = true;
+ return false;
+ }
+ }
+
+ /**
* {@link Sink} for implementing sort on SIZED reference streams.
*/
- private static final class SizedRefSortingSink<T> extends Sink.ChainedReference<T, T> {
- private final Comparator<? super T> comparator;
+ private static final class SizedRefSortingSink<T> extends AbstractRefSortingSink<T> {
private T[] array;
private int offset;
SizedRefSortingSink(Sink<? super T> sink, Comparator<? super T> comparator) {
- super(sink);
- this.comparator = comparator;
+ super(sink, comparator);
}
@Override
@@ -303,8 +347,14 @@
public void end() {
Arrays.sort(array, 0, offset, comparator);
downstream.begin(offset);
- for (int i = 0; i < offset; i++)
- downstream.accept(array[i]);
+ if (!cancellationWasRequested) {
+ for (int i = 0; i < offset; i++)
+ downstream.accept(array[i]);
+ }
+ else {
+ for (int i = 0; i < offset && !downstream.cancellationRequested(); i++)
+ downstream.accept(array[i]);
+ }
downstream.end();
array = null;
}
@@ -318,13 +368,11 @@
/**
* {@link Sink} for implementing sort on reference streams.
*/
- private static final class RefSortingSink<T> extends Sink.ChainedReference<T, T> {
- private final Comparator<? super T> comparator;
+ private static final class RefSortingSink<T> extends AbstractRefSortingSink<T> {
private ArrayList<T> list;
RefSortingSink(Sink<? super T> sink, Comparator<? super T> comparator) {
- super(sink);
- this.comparator = comparator;
+ super(sink, comparator);
}
@Override
@@ -338,7 +386,15 @@
public void end() {
list.sort(comparator);
downstream.begin(list.size());
- list.forEach(downstream::accept);
+ if (!cancellationWasRequested) {
+ list.forEach(downstream::accept);
+ }
+ else {
+ for (T t : list) {
+ if (downstream.cancellationRequested()) break;
+ downstream.accept(t);
+ }
+ }
downstream.end();
list = null;
}
@@ -350,9 +406,26 @@
}
/**
+ * Abstract {@link Sink} for implementing sort on int streams.
+ */
+ private static abstract class AbstractIntSortingSink extends Sink.ChainedInt<Integer> {
+ protected boolean cancellationWasRequested;
+
+ AbstractIntSortingSink(Sink<? super Integer> downstream) {
+ super(downstream);
+ }
+
+ @Override
+ public final boolean cancellationRequested() {
+ cancellationWasRequested = true;
+ return false;
+ }
+ }
+
+ /**
* {@link Sink} for implementing sort on SIZED int streams.
*/
- private static final class SizedIntSortingSink extends Sink.ChainedInt<Integer> {
+ private static final class SizedIntSortingSink extends AbstractIntSortingSink {
private int[] array;
private int offset;
@@ -371,8 +444,14 @@
public void end() {
Arrays.sort(array, 0, offset);
downstream.begin(offset);
- for (int i = 0; i < offset; i++)
- downstream.accept(array[i]);
+ if (!cancellationWasRequested) {
+ for (int i = 0; i < offset; i++)
+ downstream.accept(array[i]);
+ }
+ else {
+ for (int i = 0; i < offset && !downstream.cancellationRequested(); i++)
+ downstream.accept(array[i]);
+ }
downstream.end();
array = null;
}
@@ -386,7 +465,7 @@
/**
* {@link Sink} for implementing sort on int streams.
*/
- private static final class IntSortingSink extends Sink.ChainedInt<Integer> {
+ private static final class IntSortingSink extends AbstractIntSortingSink {
private SpinedBuffer.OfInt b;
IntSortingSink(Sink<? super Integer> sink) {
@@ -405,8 +484,16 @@
int[] ints = b.asPrimitiveArray();
Arrays.sort(ints);
downstream.begin(ints.length);
- for (int anInt : ints)
- downstream.accept(anInt);
+ if (!cancellationWasRequested) {
+ for (int anInt : ints)
+ downstream.accept(anInt);
+ }
+ else {
+ for (int anInt : ints) {
+ if (downstream.cancellationRequested()) break;
+ downstream.accept(anInt);
+ }
+ }
downstream.end();
}
@@ -417,9 +504,26 @@
}
/**
+ * Abstract {@link Sink} for implementing sort on long streams.
+ */
+ private static abstract class AbstractLongSortingSink extends Sink.ChainedLong<Long> {
+ protected boolean cancellationWasRequested;
+
+ AbstractLongSortingSink(Sink<? super Long> downstream) {
+ super(downstream);
+ }
+
+ @Override
+ public final boolean cancellationRequested() {
+ cancellationWasRequested = true;
+ return false;
+ }
+ }
+
+ /**
* {@link Sink} for implementing sort on SIZED long streams.
*/
- private static final class SizedLongSortingSink extends Sink.ChainedLong<Long> {
+ private static final class SizedLongSortingSink extends AbstractLongSortingSink {
private long[] array;
private int offset;
@@ -438,8 +542,14 @@
public void end() {
Arrays.sort(array, 0, offset);
downstream.begin(offset);
- for (int i = 0; i < offset; i++)
- downstream.accept(array[i]);
+ if (!cancellationWasRequested) {
+ for (int i = 0; i < offset; i++)
+ downstream.accept(array[i]);
+ }
+ else {
+ for (int i = 0; i < offset && !downstream.cancellationRequested(); i++)
+ downstream.accept(array[i]);
+ }
downstream.end();
array = null;
}
@@ -453,7 +563,7 @@
/**
* {@link Sink} for implementing sort on long streams.
*/
- private static final class LongSortingSink extends Sink.ChainedLong<Long> {
+ private static final class LongSortingSink extends AbstractLongSortingSink {
private SpinedBuffer.OfLong b;
LongSortingSink(Sink<? super Long> sink) {
@@ -472,8 +582,16 @@
long[] longs = b.asPrimitiveArray();
Arrays.sort(longs);
downstream.begin(longs.length);
- for (long aLong : longs)
- downstream.accept(aLong);
+ if (!cancellationWasRequested) {
+ for (long aLong : longs)
+ downstream.accept(aLong);
+ }
+ else {
+ for (long aLong : longs) {
+ if (downstream.cancellationRequested()) break;
+ downstream.accept(aLong);
+ }
+ }
downstream.end();
}
@@ -484,9 +602,26 @@
}
/**
+ * Abstract {@link Sink} for implementing sort on long streams.
+ */
+ private static abstract class AbstractDoubleSortingSink extends Sink.ChainedDouble<Double> {
+ protected boolean cancellationWasRequested;
+
+ AbstractDoubleSortingSink(Sink<? super Double> downstream) {
+ super(downstream);
+ }
+
+ @Override
+ public final boolean cancellationRequested() {
+ cancellationWasRequested = true;
+ return false;
+ }
+ }
+
+ /**
* {@link Sink} for implementing sort on SIZED double streams.
*/
- private static final class SizedDoubleSortingSink extends Sink.ChainedDouble<Double> {
+ private static final class SizedDoubleSortingSink extends AbstractDoubleSortingSink {
private double[] array;
private int offset;
@@ -505,8 +640,14 @@
public void end() {
Arrays.sort(array, 0, offset);
downstream.begin(offset);
- for (int i = 0; i < offset; i++)
- downstream.accept(array[i]);
+ if (!cancellationWasRequested) {
+ for (int i = 0; i < offset; i++)
+ downstream.accept(array[i]);
+ }
+ else {
+ for (int i = 0; i < offset && !downstream.cancellationRequested(); i++)
+ downstream.accept(array[i]);
+ }
downstream.end();
array = null;
}
@@ -520,7 +661,7 @@
/**
* {@link Sink} for implementing sort on double streams.
*/
- private static final class DoubleSortingSink extends Sink.ChainedDouble<Double> {
+ private static final class DoubleSortingSink extends AbstractDoubleSortingSink {
private SpinedBuffer.OfDouble b;
DoubleSortingSink(Sink<? super Double> sink) {
@@ -539,8 +680,16 @@
double[] doubles = b.asPrimitiveArray();
Arrays.sort(doubles);
downstream.begin(doubles.length);
- for (double aDouble : doubles)
- downstream.accept(aDouble);
+ if (!cancellationWasRequested) {
+ for (double aDouble : doubles)
+ downstream.accept(aDouble);
+ }
+ else {
+ for (double aDouble : doubles) {
+ if (downstream.cancellationRequested()) break;
+ downstream.accept(aDouble);
+ }
+ }
downstream.end();
}
--- a/jdk/src/share/classes/javax/swing/text/html/CSS.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/CSS.java Mon May 12 09:37:50 2014 -0700
@@ -153,6 +153,8 @@
* Fetch the default value for the attribute.
* If there is no default value (such as for
* composite attributes), null will be returned.
+ *
+ * @return default value for the attribute
*/
public String getDefaultValue() {
return defaultValue;
@@ -161,6 +163,8 @@
/**
* Indicates if the attribute should be inherited
* from the parent or not.
+ *
+ * @return true if the attribute should be inherited from the parent
*/
public boolean isInherited() {
return inherited;
@@ -1036,6 +1040,8 @@
/**
* Return the set of all possible CSS attribute keys.
+ *
+ * @return the set of all possible CSS attribute keys
*/
public static Attribute[] getAllAttributeKeys() {
Attribute[] keys = new Attribute[Attribute.allAttributes.length];
--- a/jdk/src/share/classes/javax/swing/text/html/FormView.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/FormView.java Mon May 12 09:37:50 2014 -0700
@@ -448,6 +448,8 @@
/**
* This method is responsible for submitting the form data.
* A thread is forked to undertake the submission.
+ *
+ * @param data data to submit
*/
protected void submitData(String data) {
Element form = getFormElement();
--- a/jdk/src/share/classes/javax/swing/text/html/HTML.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/HTML.java Mon May 12 09:37:50 2014 -0700
@@ -571,6 +571,9 @@
* are recognized by the default HTML reader.
* This set does not include tags that are
* manufactured by the reader.
+ *
+ * @return the set of actual HTML tags that
+ * are recognized by the default HTML reader
*/
public static Tag[] getAllTags() {
Tag[] tags = new Tag[Tag.allTags.length];
@@ -626,6 +629,7 @@
* @param key the key to use to fetch the value
* @param def the default value to use if the attribute isn't
* defined or there is an error converting to an integer
+ * @return an attribute value
*/
public static int getIntegerAttributeValue(AttributeSet attr,
Attribute key, int def) {
--- a/jdk/src/share/classes/javax/swing/text/html/HTMLDocument.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/HTMLDocument.java Mon May 12 09:37:50 2014 -0700
@@ -339,6 +339,7 @@
* <p>This is a convenience method for
* <code>getReader(int, int, int, HTML.Tag, TRUE)</code>.
*
+ * @param pos the starting position
* @param popDepth the number of <code>ElementSpec.EndTagTypes</code>
* to generate before inserting
* @param pushDepth the number of <code>ElementSpec.StartTagTypes</code>
@@ -1022,6 +1023,9 @@
* @throws IllegalArgumentException if <code>elem</code> is a leaf
* @throws IllegalStateException if an <code>HTMLEditorKit.Parser</code>
* has not been defined
+ * @throws BadLocationException if replacement is impossible because of
+ * a structural issue
+ * @throws IOException if an I/O exception occurs
* @since 1.3
*/
public void setInnerHTML(Element elem, String htmlText) throws
@@ -1099,6 +1103,9 @@
* @param htmlText the string to be parsed and inserted in place of <code>elem</code>
* @throws IllegalStateException if an HTMLEditorKit.Parser has not
* been set
+ * @throws BadLocationException if replacement is impossible because of
+ * a structural issue
+ * @throws IOException if an I/O exception occurs
* @since 1.3
*/
public void setOuterHTML(Element elem, String htmlText) throws
@@ -1177,6 +1184,9 @@
* @throws IllegalArgumentException if <code>elem</code> is a leaf
* @throws IllegalStateException if an HTMLEditorKit.Parser has not
* been set on the document
+ * @throws BadLocationException if insertion is impossible because of
+ * a structural issue
+ * @throws IOException if an I/O exception occurs
* @since 1.3
*/
public void insertAfterStart(Element elem, String htmlText) throws
@@ -1247,6 +1257,9 @@
* @throws IllegalArgumentException if <code>elem</code> is a leaf
* @throws IllegalStateException if an HTMLEditorKit.Parser has not
* been set on the document
+ * @throws BadLocationException if insertion is impossible because of
+ * a structural issue
+ * @throws IOException if an I/O exception occurs
* @since 1.3
*/
public void insertBeforeEnd(Element elem, String htmlText) throws
@@ -1310,6 +1323,9 @@
* @param htmlText the string to be parsed and inserted before <code>elem</code>
* @throws IllegalStateException if an HTMLEditorKit.Parser has not
* been set on the document
+ * @throws BadLocationException if insertion is impossible because of
+ * a structural issue
+ * @throws IOException if an I/O exception occurs
* @since 1.3
*/
public void insertBeforeStart(Element elem, String htmlText) throws
@@ -1368,6 +1384,9 @@
* @param htmlText the string to be parsed and inserted after <code>elem</code>
* @throws IllegalStateException if an HTMLEditorKit.Parser has not
* been set on the document
+ * @throws BadLocationException if insertion is impossible because of
+ * a structural issue
+ * @throws IOException if an I/O exception occurs
* @since 1.3
*/
public void insertAfterEnd(Element elem, String htmlText) throws
@@ -1890,6 +1909,7 @@
/**
* Type of tag this iterator represents.
+ * @return the tag
*/
public abstract HTML.Tag getTag();
}
@@ -2171,10 +2191,24 @@
*/
public class HTMLReader extends HTMLEditorKit.ParserCallback {
+ /**
+ * Constructs an HTMLReader using default pop and push depth and no tag to insert.
+ *
+ * @param offset the starting offset
+ */
public HTMLReader(int offset) {
this(offset, 0, 0, null);
}
+ /**
+ * Constructs an HTMLReader.
+ *
+ * @param offset the starting offset
+ * @param popDepth how many parents to ascend before insert new element
+ * @param pushDepth how many parents to descend (relative to popDepth) before
+ * inserting
+ * @param insertTag a tag to insert (may be null)
+ */
public HTMLReader(int offset, int popDepth, int pushDepth,
HTML.Tag insertTag) {
this(offset, popDepth, pushDepth, insertTag, true, false, true);
@@ -2742,6 +2776,9 @@
* all of the well-known tags will have been registered.
* This can be used to change the handling of a particular
* tag or to add support for custom tags.
+ *
+ * @param t an HTML tag
+ * @param a tag action handler
*/
protected void registerTag(HTML.Tag t, TagAction a) {
tagMap.put(t, a);
@@ -2762,6 +2799,9 @@
* tag for those actions that are shared across
* many tags. By default this does nothing and
* completely ignores the tag.
+ *
+ * @param t the HTML tag
+ * @param a the attributes
*/
public void start(HTML.Tag t, MutableAttributeSet a) {
}
@@ -2773,12 +2813,17 @@
* tag for those actions that are shared across
* many tags. By default this does nothing and
* completely ignores the tag.
+ *
+ * @param t the HTML tag
*/
public void end(HTML.Tag t) {
}
}
+ /**
+ * Action assigned by default to handle the Block task of the reader.
+ */
public class BlockAction extends TagAction {
public void start(HTML.Tag t, MutableAttributeSet attr) {
@@ -2816,6 +2861,9 @@
}
+ /**
+ * Action assigned by default to handle the Paragraph task of the reader.
+ */
public class ParagraphAction extends BlockAction {
public void start(HTML.Tag t, MutableAttributeSet a) {
@@ -2829,6 +2877,9 @@
}
}
+ /**
+ * Action assigned by default to handle the Special task of the reader.
+ */
public class SpecialAction extends TagAction {
public void start(HTML.Tag t, MutableAttributeSet a) {
@@ -2848,6 +2899,9 @@
}
+ /**
+ * Action assigned by default to handle the Hidden task of the reader.
+ */
public class HiddenAction extends TagAction {
public void start(HTML.Tag t, MutableAttributeSet a) {
@@ -3093,6 +3147,9 @@
}
}
+ /**
+ * Action assigned by default to handle the Character task of the reader.
+ */
public class CharacterAction extends TagAction {
public void start(HTML.Tag t, MutableAttributeSet attr) {
@@ -3515,6 +3572,8 @@
* context. Therefore all text that is seen belongs
* to the text area and is hence added to the
* TextAreaDocument associated with the text area.
+ *
+ * @param data the given content
*/
protected void textAreaContent(char[] data) {
try {
@@ -3529,6 +3588,8 @@
* PRE element. This synthesizes lines to hold the
* runs of text, and makes calls to addContent to
* actually add the text.
+ *
+ * @param data the given content
*/
protected void preContent(char[] data) {
int last = 0;
@@ -3550,6 +3611,9 @@
/**
* Adds an instruction to the parse buffer to create a
* block element with the given attributes.
+ *
+ * @param t an HTML tag
+ * @param attr the attribute set
*/
protected void blockOpen(HTML.Tag t, MutableAttributeSet attr) {
if (impliedP) {
@@ -3574,6 +3638,8 @@
/**
* Adds an instruction to the parse buffer to close out
* a block element of the given type.
+ *
+ * @param t the HTML tag
*/
protected void blockClose(HTML.Tag t) {
inBlock--;
@@ -3672,6 +3738,9 @@
/**
* Adds content that is basically specified entirely
* in the attribute set.
+ *
+ * @param t an HTML tag
+ * @param a the attribute set
*/
protected void addSpecialElement(HTML.Tag t, MutableAttributeSet a) {
if ((t != HTML.Tag.FRAME) && (! inParagraph) && (! inPre)) {
@@ -4049,7 +4118,13 @@
*/
Option option;
+ /**
+ * Buffer to keep building elements.
+ */
protected Vector<ElementSpec> parseBuffer = new Vector<ElementSpec>();
+ /**
+ * Current character attribute set.
+ */
protected MutableAttributeSet charAttr = new TaggedAttributeSet();
Stack<AttributeSet> charAttrStack = new Stack<AttributeSet>();
Hashtable<HTML.Tag, TagAction> tagMap;
--- a/jdk/src/share/classes/javax/swing/text/html/HTMLEditorKit.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/HTMLEditorKit.java Mon May 12 09:37:50 2014 -0700
@@ -971,6 +971,8 @@
* Parse the given stream and drive the given callback
* with the results of the parse. This method should
* be implemented to be thread-safe.
+ *
+ * @throws IOException if an I/O exception occurs
*/
public abstract void parse(Reader r, ParserCallback cb, boolean ignoreCharSet) throws IOException;
@@ -1026,6 +1028,8 @@
* or \r\n, which ever is encountered the most in parsing the
* stream.
*
+ * @param eol value of eol
+ *
* @since 1.3
*/
public void handleEndOfLineString(String eol) {
@@ -1490,6 +1494,7 @@
}
/**
+ * @param e the JEditorPane
* @return HTMLDocument of <code>e</code>.
*/
protected HTMLDocument getHTMLDocument(JEditorPane e) {
@@ -1501,6 +1506,7 @@
}
/**
+ * @param e the JEditorPane
* @return HTMLEditorKit for <code>e</code>.
*/
protected HTMLEditorKit getHTMLEditorKit(JEditorPane e) {
@@ -1514,6 +1520,10 @@
/**
* Returns an array of the Elements that contain <code>offset</code>.
* The first elements corresponds to the root.
+ *
+ * @param doc an instance of HTMLDocument
+ * @param offset value of offset
+ * @return an array of the Elements that contain <code>offset</code>
*/
protected Element[] getElementsAt(HTMLDocument doc, int offset) {
return getElementsAt(doc.getDefaultRootElement(), offset, 0);
@@ -1541,6 +1551,11 @@
* return -1 if no elements is found representing <code>tag</code>,
* or 0 if the parent of the leaf at <code>offset</code> represents
* <code>tag</code>.
+ *
+ * @param doc an instance of HTMLDocument
+ * @param offset an offset to start from
+ * @param tag tag to represent
+ * @return number of elements
*/
protected int elementCountToTag(HTMLDocument doc, int offset,
HTML.Tag tag) {
--- a/jdk/src/share/classes/javax/swing/text/html/HTMLFrameHyperlinkEvent.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/HTMLFrameHyperlinkEvent.java Mon May 12 09:37:50 2014 -0700
@@ -125,6 +125,8 @@
/**
* returns the target for the link.
+ *
+ * @return the target for the link
*/
public String getTarget() {
return targetFrame;
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java Mon May 12 09:37:50 2014 -0700
@@ -21,7 +21,7 @@
* under the License.
*/
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
*/
/*
* $Id: DOMSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
@@ -34,10 +34,12 @@
import java.io.IOException;
import java.security.*;
+import java.security.interfaces.DSAKey;
import java.security.spec.AlgorithmParameterSpec;
import org.w3c.dom.Element;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.jcp.xml.dsig.internal.SignerOutputStream;
/**
@@ -68,6 +70,8 @@
"http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384";
static final String ECDSA_SHA512 =
"http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512";
+ static final String DSA_SHA256 =
+ "http://www.w3.org/2009/xmldsig11#dsa-sha256";
/**
* Creates a <code>DOMSignatureMethod</code>.
@@ -119,6 +123,8 @@
return new SHA512withRSA(smElem);
} else if (alg.equals(SignatureMethod.DSA_SHA1)) {
return new SHA1withDSA(smElem);
+ } else if (alg.equals(DSA_SHA256)) {
+ return new SHA256withDSA(smElem);
} else if (alg.equals(ECDSA_SHA1)) {
return new SHA1withECDSA(smElem);
} else if (alg.equals(ECDSA_SHA256)) {
@@ -178,7 +184,9 @@
try {
Type type = getAlgorithmType();
if (type == Type.DSA) {
- return signature.verify(convertXMLDSIGtoASN1(sig));
+ int size = ((DSAKey)key).getParams().getQ().bitLength();
+ return signature.verify(JavaUtils.convertDsaXMLDSIGtoASN1(sig,
+ size/8));
} else if (type == Type.ECDSA) {
return signature.verify(SignatureECDSA.convertXMLDSIGtoASN1(sig));
} else {
@@ -222,7 +230,9 @@
try {
Type type = getAlgorithmType();
if (type == Type.DSA) {
- return convertASN1toXMLDSIG(signature.sign());
+ int size = ((DSAKey)key).getParams().getQ().bitLength();
+ return JavaUtils.convertDsaASN1toXMLDSIG(signature.sign(),
+ size/8);
} else if (type == Type.ECDSA) {
return SignatureECDSA.convertASN1toXMLDSIG(signature.sign());
} else {
@@ -235,101 +245,6 @@
}
}
- /**
- * Converts an ASN.1 DSA value to a XML Signature DSA Value.
- *
- * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
- * pairs; the XML Signature requires the core BigInteger values.
- *
- * @param asn1Bytes
- *
- * @throws IOException
- * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
- */
- private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[])
- throws IOException
- {
- byte rLength = asn1Bytes[3];
- int i;
-
- for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--);
-
- byte sLength = asn1Bytes[5 + rLength];
- int j;
-
- for (j = sLength;
- (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--);
-
- if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2)
- || (asn1Bytes[2] != 2) || (i > 20)
- || (asn1Bytes[4 + rLength] != 2) || (j > 20)) {
- throw new IOException("Invalid ASN.1 format of DSA signature");
- } else {
- byte xmldsigBytes[] = new byte[40];
-
- System.arraycopy(asn1Bytes, (4+rLength)-i, xmldsigBytes, 20-i, i);
- System.arraycopy(asn1Bytes, (6+rLength+sLength)-j, xmldsigBytes,
- 40 - j, j);
-
- return xmldsigBytes;
- }
- }
-
- /**
- * Converts a XML Signature DSA Value to an ASN.1 DSA value.
- *
- * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
- * pairs; the XML Signature requires the core BigInteger values.
- *
- * @param xmldsigBytes
- *
- * @throws IOException
- * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
- */
- private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[])
- throws IOException
- {
- if (xmldsigBytes.length != 40) {
- throw new IOException("Invalid XMLDSIG format of DSA signature");
- }
-
- int i;
-
- for (i = 20; (i > 0) && (xmldsigBytes[20 - i] == 0); i--);
-
- int j = i;
-
- if (xmldsigBytes[20 - i] < 0) {
- j += 1;
- }
-
- int k;
-
- for (k = 20; (k > 0) && (xmldsigBytes[40 - k] == 0); k--);
-
- int l = k;
-
- if (xmldsigBytes[40 - k] < 0) {
- l += 1;
- }
-
- byte asn1Bytes[] = new byte[6 + j + l];
-
- asn1Bytes[0] = 48;
- asn1Bytes[1] = (byte)(4 + j + l);
- asn1Bytes[2] = 2;
- asn1Bytes[3] = (byte)j;
-
- System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i);
-
- asn1Bytes[4 + j] = 2;
- asn1Bytes[5 + j] = (byte) l;
-
- System.arraycopy(xmldsigBytes, 40 - k, asn1Bytes, (6 + j + l) - k, k);
-
- return asn1Bytes;
- }
-
static final class SHA1withRSA extends DOMSignatureMethod {
SHA1withRSA(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException {
@@ -425,6 +340,25 @@
}
}
+ static final class SHA256withDSA extends DOMSignatureMethod {
+ SHA256withDSA(AlgorithmParameterSpec params)
+ throws InvalidAlgorithmParameterException {
+ super(params);
+ }
+ SHA256withDSA(Element dmElem) throws MarshalException {
+ super(dmElem);
+ }
+ public String getAlgorithm() {
+ return DSA_SHA256;
+ }
+ String getJCAAlgorithm() {
+ return "SHA256withDSA";
+ }
+ Type getAlgorithmType() {
+ return Type.DSA;
+ }
+ }
+
static final class SHA1withECDSA extends DOMSignatureMethod {
SHA1withECDSA(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException {
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java Mon May 12 09:37:50 2014 -0700
@@ -21,7 +21,7 @@
* under the License.
*/
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
*/
/*
* $Id: DOMXMLSignatureFactory.java 1333869 2012-05-04 10:42:44Z coheigea $
@@ -239,6 +239,8 @@
return new DOMSignatureMethod.SHA512withRSA(params);
} else if (algorithm.equals(SignatureMethod.DSA_SHA1)) {
return new DOMSignatureMethod.SHA1withDSA(params);
+ } else if (algorithm.equals(DOMSignatureMethod.DSA_SHA256)) {
+ return new DOMSignatureMethod.SHA256withDSA(params);
} else if (algorithm.equals(SignatureMethod.HMAC_SHA1)) {
return new DOMHMACSignatureMethod.SHA1(params);
} else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA256)) {
--- a/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/PerfDataFile.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/PerfDataFile.java Mon May 12 09:37:50 2014 -0700
@@ -233,8 +233,6 @@
* does not conform to the expected pattern
*/
public static int getLocalVmId(File file) {
- int lvmid = 0;
-
try {
// try 1.4.2 and later format first
return Integer.parseInt(file.getName());
@@ -287,31 +285,13 @@
return tmpDirName + dirNamePrefix + user + File.separator;
}
- /*
- * this static initializer would not be necessary if the
- * Solaris java.io.tmpdir property were set to /tmp by default
- */
static {
/*
- * Why is java.io.tmpdir on Solaris set to "/var/tmp/" when the
- * HotSpot JVM os:get_temp_path() method returns "/tmp/"
- *
- * Why do Solaris and Windows return a string with a trailing
- * file separator character where as Linix does not? (this change
- * seems to have occurred sometime during hopper beta)
+ * For this to work, the target VM and this code need to use
+ * the same directory. Instead of guessing which directory the
+ * VM is using, we will ask.
*/
- String tmpdir = System.getProperty("java.io.tmpdir");
-
- if (tmpdir.compareTo("/var/tmp/") == 0) {
- /*
- * shared memory files are created in /tmp. Interestingly,
- * java.io.tmpdir is set to "/var/tmp/" on Solaris and Linux,
- * but os::get_temp_directory() is set to "/tmp/" on these
- * platforms. the java.io.logging packages also makes reference
- * to java.io.tmpdir.
- */
- tmpdir = "/tmp/";
- }
+ String tmpdir = sun.misc.VMSupport.getVMTemporaryDirectory();
/*
* Assure that the string returned has a trailing File.separator
--- a/jdk/src/share/classes/sun/launcher/LauncherHelper.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/sun/launcher/LauncherHelper.java Mon May 12 09:37:50 2014 -0700
@@ -69,6 +69,14 @@
public enum LauncherHelper {
INSTANCE;
+
+ // used to identify JavaFX applications
+ private static final String JAVAFX_APPLICATION_MARKER =
+ "JavaFX-Application-Class";
+ private static final String JAVAFX_APPLICATION_CLASS_NAME =
+ "javafx.application.Application";
+ private static final String JAVAFX_FXHELPER_CLASS_NAME_SUFFIX =
+ "sun.launcher.LauncherHelper$FXHelper";
private static final String MAIN_CLASS = "Main-Class";
private static StringBuilder outBuf = new StringBuilder();
@@ -418,7 +426,8 @@
* exists to enforce compliance with the jar specification
*/
if (mainAttrs.containsKey(
- new Attributes.Name(FXHelper.JAVAFX_APPLICATION_MARKER))) {
+ new Attributes.Name(JAVAFX_APPLICATION_MARKER))) {
+ FXHelper.setFXLaunchParameters(jarname, LM_JAR);
return FXHelper.class.getName();
}
@@ -516,9 +525,9 @@
* the main class may or may not have a main method, so do this before
* validating the main class.
*/
- if (mainClass.equals(FXHelper.class) ||
- FXHelper.doesExtendFXApplication(mainClass)) {
- // Will abort() if there are problems with the FX runtime
+ if (JAVAFX_FXHELPER_CLASS_NAME_SUFFIX.equals(mainClass.getName()) ||
+ doesExtendFXApplication(mainClass)) {
+ // Will abort() if there are problems with FX runtime
FXHelper.setFXLaunchParameters(what, mode);
return FXHelper.class;
}
@@ -537,6 +546,21 @@
return appClass;
}
+ /*
+ * Check if the given class is a JavaFX Application class. This is done
+ * in a way that does not cause the Application class to load or throw
+ * ClassNotFoundException if the JavaFX runtime is not available.
+ */
+ private static boolean doesExtendFXApplication(Class<?> mainClass) {
+ for (Class<?> sc = mainClass.getSuperclass(); sc != null;
+ sc = sc.getSuperclass()) {
+ if (sc.getName().equals(JAVAFX_APPLICATION_CLASS_NAME)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
// Check the existence and signature of main and abort if incorrect
static void validateMainClass(Class<?> mainClass) {
Method mainMethod;
@@ -545,7 +569,7 @@
} catch (NoSuchMethodException nsme) {
// invalid main or not FX application, abort with an error
abort(null, "java.launcher.cls.error4", mainClass.getName(),
- FXHelper.JAVAFX_APPLICATION_CLASS_NAME);
+ JAVAFX_APPLICATION_CLASS_NAME);
return; // Avoid compiler issues
}
@@ -668,11 +692,7 @@
}
static final class FXHelper {
- // Marker entry in jar manifest that designates a JavaFX application jar
- private static final String JAVAFX_APPLICATION_MARKER =
- "JavaFX-Application-Class";
- private static final String JAVAFX_APPLICATION_CLASS_NAME =
- "javafx.application.Application";
+
private static final String JAVAFX_LAUNCHER_CLASS_NAME =
"com.sun.javafx.application.LauncherImpl";
@@ -742,21 +762,6 @@
}
}
- /*
- * Check if the given class is a JavaFX Application class. This is done
- * in a way that does not cause the Application class to load or throw
- * ClassNotFoundException if the JavaFX runtime is not available.
- */
- private static boolean doesExtendFXApplication(Class<?> mainClass) {
- for (Class<?> sc = mainClass.getSuperclass(); sc != null;
- sc = sc.getSuperclass()) {
- if (sc.getName().equals(JAVAFX_APPLICATION_CLASS_NAME)) {
- return true;
- }
- }
- return false;
- }
-
public static void main(String... args) throws Exception {
if (fxLauncherMethod == null
|| fxLaunchMode == null
--- a/jdk/src/share/classes/sun/misc/VMSupport.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/sun/misc/VMSupport.java Mon May 12 09:37:50 2014 -0700
@@ -97,4 +97,14 @@
throw new RuntimeException(ioe.getMessage());
}
}
+
+ /*
+ * Return the temporary directory that the VM uses for the attach
+ * and perf data files.
+ *
+ * It is important that this directory is well-known and the
+ * same for all VM instances. It cannot be affected by configuration
+ * variables such as java.io.tmpdir.
+ */
+ public static native String getVMTemporaryDirectory();
}
--- a/jdk/src/share/classes/sun/nio/fs/AbstractPoller.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/sun/nio/fs/AbstractPoller.java Mon May 12 09:37:50 2014 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 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
@@ -100,8 +100,6 @@
// validate arguments before request to poller
if (dir == null)
throw new NullPointerException();
- if (events.length == 0)
- throw new IllegalArgumentException("No events to register");
Set<WatchEvent.Kind<?>> eventSet = new HashSet<>(events.length);
for (WatchEvent.Kind<?> event: events) {
// standard events
@@ -114,17 +112,16 @@
}
// OVERFLOW is ignored
- if (event == StandardWatchEventKinds.OVERFLOW) {
- if (events.length == 1)
- throw new IllegalArgumentException("No events to register");
+ if (event == StandardWatchEventKinds.OVERFLOW)
continue;
- }
// null/unsupported
if (event == null)
throw new NullPointerException("An element in event set is 'null'");
throw new UnsupportedOperationException(event.name());
}
+ if (eventSet.isEmpty())
+ throw new IllegalArgumentException("No events to register");
return (WatchKey)invoke(RequestType.REGISTER, dir, eventSet, modifiers);
}
@@ -192,14 +189,17 @@
* the request.
*/
Object awaitResult() {
+ boolean interrupted = false;
synchronized (this) {
while (!completed) {
try {
wait();
} catch (InterruptedException x) {
- // ignore
+ interrupted = true;
}
}
+ if (interrupted)
+ Thread.currentThread().interrupt();
return result;
}
}
--- a/jdk/src/share/classes/sun/security/krb5/internal/rcache/DflCache.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/rcache/DflCache.java Mon May 12 09:37:50 2014 -0700
@@ -39,6 +39,7 @@
import java.security.AccessController;
import java.util.*;
+import com.sun.security.auth.module.UnixSystem;
import sun.security.action.GetPropertyAction;
import sun.security.krb5.internal.KerberosTime;
import sun.security.krb5.internal.Krb5;
@@ -105,14 +106,14 @@
private final String source;
- private static int uid;
+ private static long uid;
static {
try {
// Available on Solaris, Linux and Mac. Otherwise, no _euid suffix
- Class<?> clazz = Class.forName("com.sun.security.auth.module.UnixSystem");
- uid = (int)(long)(Long)
- clazz.getMethod("getUid").invoke(clazz.newInstance());
- } catch (Exception e) {
+ UnixSystem us = new com.sun.security.auth.module.UnixSystem();
+ uid = us.getUid();
+ } catch (Throwable e) {
+ // Cannot be only Exception, might be UnsatisfiedLinkError
uid = -1;
}
}
--- a/jdk/src/share/classes/sun/security/ssl/ByteBufferInputStream.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/sun/security/ssl/ByteBufferInputStream.java Mon May 12 09:37:50 2014 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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,8 @@
if (bb.remaining() == 0) {
return -1;
}
- return bb.get();
+
+ return (bb.get() & 0xFF); // need to be in the range 0 to 255
}
/**
--- a/jdk/src/share/classes/sun/security/ssl/EngineInputRecord.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/sun/security/ssl/EngineInputRecord.java Mon May 12 09:37:50 2014 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -109,14 +109,8 @@
ProtocolVersion recordVersion =
ProtocolVersion.valueOf(buf.get(pos + 1), buf.get(pos + 2));
- // Check if too old (currently not possible)
- // or if the major version does not match.
- // The actual version negotiation is in the handshaker classes
- if ((recordVersion.v < ProtocolVersion.MIN.v)
- || (recordVersion.major > ProtocolVersion.MAX.major)) {
- throw new SSLException(
- "Unsupported record version " + recordVersion);
- }
+ // check the record version
+ checkRecordVersion(recordVersion, false);
/*
* Reasonably sure this is a V3, disable further checks.
@@ -147,18 +141,8 @@
ProtocolVersion recordVersion =
ProtocolVersion.valueOf(buf.get(pos + 3), buf.get(pos + 4));
- // Check if too old (currently not possible)
- // or if the major version does not match.
- // The actual version negotiation is in the handshaker classes
- if ((recordVersion.v < ProtocolVersion.MIN.v)
- || (recordVersion.major > ProtocolVersion.MAX.major)) {
-
- // if it's not SSLv2, we're out of here.
- if (recordVersion.v != ProtocolVersion.SSL20Hello.v) {
- throw new SSLException(
- "Unsupported record version " + recordVersion);
- }
- }
+ // check the record version
+ checkRecordVersion(recordVersion, true);
/*
* Client or Server Hello
@@ -406,14 +390,9 @@
ProtocolVersion recordVersion = ProtocolVersion.valueOf(
srcBB.get(srcPos + 1), srcBB.get(srcPos + 2));
- // Check if too old (currently not possible)
- // or if the major version does not match.
- // The actual version negotiation is in the handshaker classes
- if ((recordVersion.v < ProtocolVersion.MIN.v)
- || (recordVersion.major > ProtocolVersion.MAX.major)) {
- throw new SSLException(
- "Unsupported record version " + recordVersion);
- }
+
+ // check the record version
+ checkRecordVersion(recordVersion, false);
/*
* It's really application data. How much to consume?
--- a/jdk/src/share/classes/sun/security/ssl/InputRecord.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/sun/security/ssl/InputRecord.java Mon May 12 09:37:50 2014 -0700
@@ -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
@@ -534,19 +534,35 @@
}
/**
+ * Return true if the specified record protocol version is out of the
+ * range of the possible supported versions.
+ */
+ static void checkRecordVersion(ProtocolVersion version,
+ boolean allowSSL20Hello) throws SSLException {
+ // Check if the record version is too old (currently not possible)
+ // or if the major version does not match.
+ //
+ // The actual version negotiation is in the handshaker classes
+ if ((version.v < ProtocolVersion.MIN.v) ||
+ ((version.major & 0xFF) > (ProtocolVersion.MAX.major & 0xFF))) {
+
+ // if it's not SSLv2, we're out of here.
+ if (!allowSSL20Hello ||
+ (version.v != ProtocolVersion.SSL20Hello.v)) {
+ throw new SSLException("Unsupported record version " + version);
+ }
+ }
+ }
+
+ /**
* Read a SSL/TLS record. Throw an IOException if the format is invalid.
*/
private void readV3Record(InputStream s, OutputStream o)
throws IOException {
ProtocolVersion recordVersion = ProtocolVersion.valueOf(buf[1], buf[2]);
- // Check if too old (currently not possible)
- // or if the major version does not match.
- // The actual version negotiation is in the handshaker classes
- if ((recordVersion.v < ProtocolVersion.MIN.v)
- || (recordVersion.major > ProtocolVersion.MAX.major)) {
- throw new SSLException(
- "Unsupported record version " + recordVersion);
- }
+
+ // check the record version
+ checkRecordVersion(recordVersion, false);
/*
* Get and check length, then the data.
--- a/jdk/src/share/classes/sun/security/ssl/ProtocolVersion.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/classes/sun/security/ssl/ProtocolVersion.java Mon May 12 09:37:50 2014 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 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
@@ -101,7 +101,7 @@
this.v = v;
this.name = name;
major = (byte)(v >>> 8);
- minor = (byte)(v & 0xff);
+ minor = (byte)(v & 0xFF);
}
// private
@@ -117,8 +117,8 @@
} else if (v == SSL20Hello.v) {
return SSL20Hello;
} else {
- int major = (v >>> 8) & 0xff;
- int minor = v & 0xff;
+ int major = (v >>> 8) & 0xFF;
+ int minor = v & 0xFF;
return new ProtocolVersion(v, "Unknown-" + major + "." + minor);
}
}
@@ -128,10 +128,7 @@
* numbers. Never throws exceptions.
*/
public static ProtocolVersion valueOf(int major, int minor) {
- major &= 0xff;
- minor &= 0xff;
- int v = (major << 8) | minor;
- return valueOf(v);
+ return valueOf(((major & 0xFF) << 8) | (minor & 0xFF));
}
/**
--- a/jdk/src/share/javavm/export/jvm.h Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/javavm/export/jvm.h Mon May 12 09:37:50 2014 -0700
@@ -1331,6 +1331,9 @@
JNIEXPORT jobject JNICALL
JVM_InitAgentProperties(JNIEnv *env, jobject agent_props);
+JNIEXPORT jstring JNICALL
+JVM_GetTemporaryDirectory(JNIEnv *env);
+
/* Generics reflection support.
*
* Returns information about the given class's EnclosingMethod
--- a/jdk/src/share/native/sun/misc/VMSupport.c Mon May 05 12:48:07 2014 -0700
+++ b/jdk/src/share/native/sun/misc/VMSupport.c Mon May 12 09:37:50 2014 -0700
@@ -53,3 +53,9 @@
}
return (*InitAgentProperties_fp)(env, props);
}
+
+JNIEXPORT jstring JNICALL
+Java_sun_misc_VMSupport_getVMTemporaryDirectory(JNIEnv *env, jclass cls)
+{
+ return JVM_GetTemporaryDirectory(env);
+}
--- a/jdk/test/ProblemList.txt Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/ProblemList.txt Mon May 12 09:37:50 2014 -0700
@@ -249,6 +249,18 @@
# jdk_jdi
+# 6983531
+com/sun/jdi/BadHandshakeTest.java linux-all, windows-all
+
+# 8004127
+com/sun/jdi/RedefineImplementor.sh generic-all
+
+# 8031555
+com/sun/jdi/JdbMethodExitTest.sh generic-all
+
+# 8041934
+com/sun/jdi/RepStep.java generic-all
+
############################################################################
# jdk_util
@@ -270,4 +282,10 @@
# 8033104
sun/jvmstat/monitor/MonitoredVm/CR6672135.java generic-all
+# 8041989
+sun/tools/jstatd/TestJstatdDefaults.java generic-all
+
+# 8037285
+sun/tools/jstatd/TestJstatdServer.java generic-all
+
############################################################################
--- a/jdk/test/TEST.groups Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/TEST.groups Mon May 12 09:37:50 2014 -0700
@@ -1,4 +1,4 @@
-# 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
@@ -155,6 +155,15 @@
jdk_jdi = \
com/sun/jdi
+# java launcher specific tests, Note: do not include this group into any groups
+# that potentially could be included into a jprt test rule, as the complementary
+# closed group includes awt SplashScreen and these tests may not run
+# satisfacotorily on all platforms and profiles thus this group must always
+# be a stand-alone group
+jdk_launcher = \
+ tools/launcher \
+ sun/tools
+
#
# Tool (and tool API) tests are split into core and svc groups
#
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/security/auth/module/AllPlatforms.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,74 @@
+/*
+ * 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 8039951
+ * @summary com.sun.security.auth.module missing classes on some platforms
+ * @run main/othervm AllPlatforms
+ */
+
+import javax.security.auth.login.Configuration;
+import javax.security.auth.login.LoginContext;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
+public class AllPlatforms {
+ public static void main(String[] args) throws Exception {
+ login("cross-platform",
+ "UnixLoginModule", "optional",
+ "NTLoginModule", "optional",
+ "SolarisLoginModule", "optional");
+ try {
+ login("windows", "NTLoginModule", "required");
+ login("unix", "UnixLoginModule", "required");
+ login("solaris", "SolarisLoginModule", "required");
+ } catch (Exception e) {
+ e.printStackTrace(System.out);
+ if (e.toString().contains("UnsatisfiedLinkError")) {
+ throw new Exception("This is ugly");
+ }
+ }
+ }
+
+ static void login(String test, String... conf) throws Exception {
+ System.out.println("Testing " + test + "...");
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("hello {\n");
+ for (int i=0; i<conf.length; i+=2) {
+ sb.append(" com.sun.security.auth.module." + conf[i]
+ + " " + conf[i+1] + ";\n");
+ }
+ sb.append("};\n");
+ Files.write(Paths.get(test), sb.toString().getBytes());
+
+ // Must be called. Configuration has an internal static field.
+ Configuration.setConfiguration(null);
+ System.setProperty("java.security.auth.login.config", test);
+
+ LoginContext lc = new LoginContext("hello");
+ lc.login();
+ System.out.println(lc.getSubject());
+ }
+}
--- a/jdk/test/com/sun/tools/attach/BasicTests.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/com/sun/tools/attach/BasicTests.java Mon May 12 09:37:50 2014 -0700
@@ -38,7 +38,7 @@
* @bug 6173612 6273707 6277253 6335921 6348630 6342019 6381757
* @summary Basic unit tests for the VM attach mechanism.
* @library /lib/testlibrary
- * @run build Agent BadAgent RedefineAgent Application Shutdown RedefineDummy
+ * @run build Agent BadAgent RedefineAgent Application Shutdown RedefineDummy RunnerUtil
* @run main BasicTests
*
* This test will perform a number of basic attach tests.
@@ -238,19 +238,17 @@
// Test 6 - list method should list the target VM
System.out.println(" - Test: VirtualMachine.list");
List<VirtualMachineDescriptor> l = VirtualMachine.list();
- if (!l.isEmpty()) {
- boolean found = false;
- for (VirtualMachineDescriptor vmd: l) {
- if (vmd.id().equals(pid)) {
- found = true;
- break;
- }
+ boolean found = false;
+ for (VirtualMachineDescriptor vmd: l) {
+ if (vmd.id().equals(pid)) {
+ found = true;
+ break;
}
- if (found) {
- System.out.println(" - " + pid + " found.");
- } else {
- throw new RuntimeException(pid + " not found in VM list");
- }
+ }
+ if (found) {
+ System.out.println(" - " + pid + " found.");
+ } else {
+ throw new RuntimeException(pid + " not found in VM list");
}
// test 7 - basic hashCode/equals tests
--- a/jdk/test/com/sun/tools/attach/RunnerUtil.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/com/sun/tools/attach/RunnerUtil.java Mon May 12 09:37:50 2014 -0700
@@ -24,12 +24,11 @@
import java.io.IOException;
import java.io.File;
import java.nio.file.Files;
-import java.nio.file.Path;
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
+
import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.JDKToolLauncher;
import jdk.testlibrary.ProcessTools;
import jdk.testlibrary.Utils;
import jdk.testlibrary.ProcessThread;
@@ -39,6 +38,7 @@
* (Test runner = class that launch a test)
*/
public class RunnerUtil {
+
/**
* The Application process must be run concurrently with our tests since
* the tests will attach to the Application.
@@ -49,16 +49,31 @@
*
* The Application will write its pid and shutdownPort in the given outFile.
*/
- public static ProcessThread startApplication(String outFile) throws Throwable {
+ public static ProcessThread startApplication(String outFile, String... additionalOpts) throws Throwable {
String classpath = System.getProperty("test.class.path", ".");
- String[] args = Utils.addTestJavaOpts(
- "-Dattach.test=true", "-classpath", classpath, "Application", outFile);
+ String[] myArgs = concat(additionalOpts, new String [] { "-Dattach.test=true", "-classpath", classpath, "Application", outFile });
+ String[] args = Utils.addTestJavaOpts(myArgs);
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args);
ProcessThread pt = new ProcessThread("runApplication", pb);
pt.start();
return pt;
}
+ public static String[] concat(String[] a, String[] b) {
+ if (a == null) {
+ return b;
+ }
+ if (b == null) {
+ return a;
+ }
+ int aLen = a.length;
+ int bLen = b.length;
+ String[] c = new String[aLen + bLen];
+ System.arraycopy(a, 0, c, 0, aLen);
+ System.arraycopy(b, 0, c, aLen, bLen);
+ return c;
+ }
+
/**
* Will stop the running Application.
* First tries to shutdown nicely by connecting to the shut down port.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/tools/attach/TempDirTest.java Mon May 12 09:37:50 2014 -0700
@@ -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.
+ *
+ * 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 com.sun.tools.attach.*;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Properties;
+import java.util.List;
+import java.io.File;
+
+import jdk.testlibrary.OutputAnalyzer;
+import jdk.testlibrary.ProcessTools;
+import jdk.testlibrary.ProcessThread;
+
+/*
+ * @test
+ * @bug 8033104
+ * @summary Test to make sure attach and jvmstat works correctly when java.io.tmpdir is set
+ * @library /lib/testlibrary
+ * @run build Application Shutdown RunnerUtil
+ * @run main/timeout=10 TempDirTest
+ */
+
+public class TempDirTest {
+
+ public static void main(String args[]) throws Throwable {
+
+ Path clientTmpDir = Files.createTempDirectory("TempDirTest-client");
+ clientTmpDir.toFile().deleteOnExit();
+ Path targetTmpDir = Files.createTempDirectory("TempDirTest-target");
+ targetTmpDir.toFile().deleteOnExit();
+
+ // run the test with all possible combinations of setting java.io.tmpdir
+ runExperiment(null, null);
+ runExperiment(clientTmpDir, null);
+ runExperiment(clientTmpDir, targetTmpDir);
+ runExperiment(null, targetTmpDir);
+
+ }
+
+ private static int counter = 0;
+
+ /*
+ * The actual test is in the nested class TestMain.
+ * The responsibility of this class is to:
+ * 1. Start the Application class in a separate process.
+ * 2. Find the pid and shutdown port of the running Application.
+ * 3. Launches the tests in nested class TestMain that will attach to the Application.
+ * 4. Shut down the Application.
+ */
+ public static void runExperiment(Path clientTmpDir, Path targetTmpDir) throws Throwable {
+
+ System.out.print("### Running tests with overridden tmpdir for");
+ System.out.print(" client: " + (clientTmpDir == null ? "no" : "yes"));
+ System.out.print(" target: " + (targetTmpDir == null ? "no" : "yes"));
+ System.out.println(" ###");
+
+ final String pidFile = "TempDirTest.Application.pid-" + counter++;
+ ProcessThread processThread = null;
+ RunnerUtil.ProcessInfo info = null;
+ try {
+ String[] tmpDirArg = null;
+ if (targetTmpDir != null) {
+ tmpDirArg = new String[] {"-Djava.io.tmpdir=" + targetTmpDir};
+ }
+ processThread = RunnerUtil.startApplication(pidFile, tmpDirArg);
+ info = RunnerUtil.readProcessInfo(pidFile);
+ launchTests(info.pid, clientTmpDir);
+ } catch (Throwable t) {
+ System.out.println("TempDirTest got unexpected exception: " + t);
+ t.printStackTrace();
+ throw t;
+ } finally {
+ // Make sure the Application process is stopped.
+ RunnerUtil.stopApplication(info.shutdownPort, processThread);
+ }
+ }
+
+ /**
+ * Runs the actual tests in nested class TestMain.
+ * The reason for running the tests in a separate process
+ * is that we need to modify the class path and
+ * the -Djava.io.tmpdir property.
+ */
+ private static void launchTests(int pid, Path clientTmpDir) throws Throwable {
+ final String sep = File.separator;
+
+ // Need to add jdk/lib/tools.jar to classpath.
+ String classpath =
+ System.getProperty("test.class.path", "") + File.pathSeparator +
+ System.getProperty("test.jdk", ".") + sep + "lib" + sep + "tools.jar";
+
+ String[] tmpDirArg = null;
+ if (clientTmpDir != null) {
+ tmpDirArg = new String [] {"-Djava.io.tmpdir=" + clientTmpDir};
+ }
+
+ // Arguments : [-Djava.io.tmpdir=] -classpath cp TempDirTest$TestMain pid
+ String[] args = RunnerUtil.concat(
+ tmpDirArg,
+ new String[] {
+ "-classpath",
+ classpath,
+ "TempDirTest$TestMain",
+ Integer.toString(pid) });
+ OutputAnalyzer output = ProcessTools.executeTestJvm(args);
+ output.shouldHaveExitValue(0);
+ }
+
+ /**
+ * This is the actual test. It will attach to the running Application
+ * and perform a number of basic attach tests.
+ */
+ public static class TestMain {
+ public static void main(String args[]) throws Exception {
+ String pid = args[0];
+
+ // Test 1 - list method should list the target VM
+ System.out.println(" - Test: VirtualMachine.list");
+ List<VirtualMachineDescriptor> l = VirtualMachine.list();
+ boolean found = false;
+ for (VirtualMachineDescriptor vmd: l) {
+ if (vmd.id().equals(pid)) {
+ found = true;
+ break;
+ }
+ }
+ if (found) {
+ System.out.println(" - " + pid + " found.");
+ } else {
+ throw new RuntimeException(pid + " not found in VM list");
+ }
+
+ // Test 2 - try to attach and verify connection
+
+ System.out.println(" - Attaching to application ...");
+ VirtualMachine vm = VirtualMachine.attach(pid);
+
+ System.out.println(" - Test: system properties in target VM");
+ Properties props = vm.getSystemProperties();
+ String value = props.getProperty("attach.test");
+ if (value == null || !value.equals("true")) {
+ throw new RuntimeException("attach.test property not set");
+ }
+ System.out.println(" - attach.test property set as expected");
+ }
+ }
+}
--- a/jdk/test/com/sun/tools/attach/java.policy.allow Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/com/sun/tools/attach/java.policy.allow Mon May 12 09:37:50 2014 -0700
@@ -13,7 +13,6 @@
permission java.lang.RuntimePermission "accessClassInPackage.sun.jvmstat.monitor";
permission java.lang.RuntimePermission "loadLibrary.attach";
permission java.util.PropertyPermission "sun.jvmstat.*", "read";
- permission java.util.PropertyPermission "java.io.tmpdir", "read";
/* to read configuration file in META-INF/services, and write/delete .attach_pid<pid> */
permission java.io.FilePermission "<<ALL FILES>>", "read,write,delete";
--- a/jdk/test/com/sun/tools/attach/java.policy.deny Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/com/sun/tools/attach/java.policy.deny Mon May 12 09:37:50 2014 -0700
@@ -11,7 +11,6 @@
permission java.lang.RuntimePermission "accessClassInPackage.sun.tools.attach";
permission java.lang.RuntimePermission "loadLibrary.attach";
permission java.util.PropertyPermission "sun.jvmstat.*", "read";
- permission java.util.PropertyPermission "java.io.tmpdir", "read";
/* to read configuration file in META-INF/services, and write/delete .attach_pid<pid> */
permission java.io.FilePermission "<<ALL FILES>>", "read,write,delete";
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/math/BigInteger/PrimeTest.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,230 @@
+/*
+ * 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.
+ */
+
+/*
+ * @test
+ * @bug 8026236
+ * @summary test primality verification methods in BigInteger
+ * @author bpb
+ */
+import java.math.BigInteger;
+import java.util.BitSet;
+import java.util.HashSet;
+import java.util.List;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.SplittableRandom;
+import java.util.TreeSet;
+import static java.util.stream.Collectors.toCollection;
+import static java.util.stream.Collectors.toList;
+
+public class PrimeTest {
+
+ private static final int DEFAULT_UPPER_BOUND = 1299709; // 100000th prime
+ private static final int DEFAULT_CERTAINTY = 100;
+ private static final int NUM_NON_PRIMES = 10000;
+
+ /**
+ * Run the test.
+ *
+ * @param args The parameters.
+ * @throws Exception on failure
+ */
+ public static void main(String[] args) throws Exception {
+ // Prepare arguments
+ int upperBound = args.length > 0 ? Integer.valueOf(args[0]) : DEFAULT_UPPER_BOUND;
+ int certainty = args.length > 1 ? Integer.valueOf(args[1]) : DEFAULT_CERTAINTY;
+ boolean parallel = args.length > 2 ? Boolean.valueOf(args[2]) : true;
+
+ // Echo parameter settings
+ System.out.println("Upper bound = " + upperBound
+ + "\nCertainty = " + certainty
+ + "\nParallel = " + parallel);
+
+ // Get primes through specified bound (inclusive) and Integer.MAX_VALUE
+ NavigableSet<BigInteger> primes = getPrimes(upperBound);
+
+ // Check whether known primes are identified as such
+ boolean primeTest = checkPrime(primes, certainty, parallel);
+ System.out.println("Prime test result: " + (primeTest ? "SUCCESS" : "FAILURE"));
+ if (!primeTest) {
+ System.err.println("Prime test failed");
+ }
+
+ // Check whether known non-primes are not identified as primes
+ boolean nonPrimeTest = checkNonPrime(primes, certainty);
+ System.out.println("Non-prime test result: " + (nonPrimeTest ? "SUCCESS" : "FAILURE"));
+
+ boolean mersennePrimeTest = checkMersennePrimes(certainty);
+ System.out.println("Mersenne test result: " + (mersennePrimeTest ? "SUCCESS" : "FAILURE"));
+
+ if (!primeTest || !nonPrimeTest || !mersennePrimeTest) {
+ throw new Exception("PrimeTest FAILED!");
+ }
+
+ System.out.println("PrimeTest succeeded!");
+ }
+
+ /**
+ * Create a {@code BitSet} wherein a set bit indicates the corresponding
+ * index plus 2 is prime. That is, if bit N is set, then the integer N + 2
+ * is prime. The values 0 and 1 are intentionally excluded. See the
+ * <a
+ * href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_description">
+ * Sieve of Eratosthenes</a> algorithm description for more information.
+ *
+ * @param upperBound The maximum prime to allow
+ * @return bits indicating which indexes represent primes
+ */
+ private static BitSet createPrimes(int upperBound) {
+ int nbits = upperBound - 1;
+ BitSet bs = new BitSet(nbits);
+ for (int p = 2; p * p < upperBound;) {
+ for (int i = p * p; i < nbits + 2; i += p) {
+ bs.set(i - 2, true);
+ }
+ do {
+ ++p;
+ } while (p > 1 && bs.get(p - 2));
+ }
+ bs.flip(0, nbits);
+ return bs;
+ }
+
+ /**
+ * Load the primes up to the specified bound (inclusive) into a
+ * {@code NavigableSet}, appending the prime {@code Integer.MAX_VALUE}.
+ *
+ * @param upperBound The maximum prime to allow
+ * @return a set of primes
+ */
+ private static NavigableSet<BigInteger> getPrimes(int upperBound) {
+ BitSet bs = createPrimes(upperBound);
+ NavigableSet<BigInteger> primes = bs.stream()
+ .mapToObj(p -> BigInteger.valueOf(p + 2))
+ .collect(toCollection(TreeSet::new));
+ primes.add(BigInteger.valueOf(Integer.MAX_VALUE));
+ System.out.println(String.format("Created %d primes", primes.size()));
+ return primes;
+ }
+
+ /**
+ * Verifies whether the fraction of probable primes detected is at least 1 -
+ * 1/2^certainty.
+ *
+ * @return true if and only if the test succeeds
+ */
+ private static boolean checkPrime(Set<BigInteger> primes,
+ int certainty,
+ boolean parallel) {
+ long probablePrimes = (parallel ? primes.parallelStream() : primes.stream())
+ .filter(bi -> bi.isProbablePrime(certainty))
+ .count();
+
+ // N = certainty / 2
+ // Success if p/t >= 1 - 1/4^N
+ // or (p/t)*4^N >= 4^N - 1
+ // or p*4^N >= t*(4^N - 1)
+ BigInteger p = BigInteger.valueOf(probablePrimes);
+ BigInteger t = BigInteger.valueOf(primes.size());
+ BigInteger fourToTheC = BigInteger.valueOf(4).pow(certainty / 2);
+ BigInteger fourToTheCMinusOne = fourToTheC.subtract(BigInteger.ONE);
+ BigInteger left = p.multiply(fourToTheC);
+ BigInteger right = t.multiply(fourToTheCMinusOne);
+
+ if (left.compareTo(right) < 0) {
+ System.err.println("Probable prime certainty test failed");
+ }
+
+ return left.compareTo(right) >= 0;
+ }
+
+ /**
+ * Verifies whether all {@code BigInteger}s in the tested range for which
+ * {@code isProbablePrime()} returns {@code false} are <i>not</i>
+ * prime numbers.
+ *
+ * @return true if and only if the test succeeds
+ */
+ private static boolean checkNonPrime(NavigableSet<BigInteger> primes,
+ int certainty) {
+ int maxPrime = DEFAULT_UPPER_BOUND;
+ try {
+ maxPrime = primes.last().intValueExact();
+ } catch (ArithmeticException e) {
+ // ignore it
+ }
+
+ // Create a list of non-prime BigIntegers.
+ List<BigInteger> nonPrimeBigInts = (new SplittableRandom())
+ .ints(NUM_NON_PRIMES, 2, maxPrime).mapToObj(BigInteger::valueOf)
+ .filter(b -> !b.isProbablePrime(certainty)).collect(toList());
+
+ // If there are any non-probable primes also in the primes list then fail.
+ boolean failed = nonPrimeBigInts.stream().anyMatch(primes::contains);
+
+ // In the event, print which purported non-primes were actually prime.
+ if (failed) {
+ for (BigInteger bigInt : nonPrimeBigInts) {
+ if (primes.contains(bigInt)) {
+ System.err.println("Prime value thought to be non-prime: " + bigInt);
+ }
+ }
+ }
+
+ return !failed;
+ }
+
+ /**
+ * Verifies whether a specified subset of Mersenne primes are correctly
+ * identified as being prime. See
+ * <a href="https://en.wikipedia.org/wiki/Mersenne_prime">Mersenne prime</a>
+ * for more information.
+ *
+ * @return true if and only if the test succeeds
+ */
+ private static boolean checkMersennePrimes(int certainty) {
+ int[] MERSENNE_EXPONENTS = {
+ 2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203,
+ 2281, 3217, 4253, // uncomment remaining array elements to make this test run a long time
+ /* 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497,
+ 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269,
+ 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951,
+ 30402457, 32582657, 37156667, 42643801, 43112609, 57885161 */
+ };
+ System.out.println("Checking first "+MERSENNE_EXPONENTS.length+" Mersenne primes");
+
+ boolean result = true;
+ for (int n : MERSENNE_EXPONENTS) {
+ BigInteger mp = BigInteger.ONE.shiftLeft(n).subtract(BigInteger.ONE);
+ if (!mp.isProbablePrime(certainty)) {
+ System.err.println("Mp with p = "+n+" not classified as prime");
+ result = false;
+ }
+ }
+
+ return result;
+ }
+}
--- a/jdk/test/java/nio/file/WatchService/Basic.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/java/nio/file/WatchService/Basic.java Mon May 12 09:37:50 2014 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 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,7 +22,7 @@
*/
/* @test
- * @bug 4313887 6838333 7017446
+ * @bug 4313887 6838333 7017446 8011537 8042470
* @summary Unit test for java.nio.file.WatchService
* @library ..
* @run main Basic
@@ -295,24 +295,31 @@
// IllegalArgumentException
System.out.println("IllegalArgumentException tests...");
try {
- dir.register(watcher, new WatchEvent.Kind<?>[]{ } );
+ dir.register(watcher /*empty event list*/);
throw new RuntimeException("IllegalArgumentException not thrown");
} catch (IllegalArgumentException x) {
}
try {
// OVERFLOW is ignored so this is equivalent to the empty set
- dir.register(watcher, new WatchEvent.Kind<?>[]{ OVERFLOW });
+ dir.register(watcher, OVERFLOW);
+ throw new RuntimeException("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException x) {
+ }
+ try {
+ // OVERFLOW is ignored even if specified multiple times
+ dir.register(watcher, OVERFLOW, OVERFLOW);
throw new RuntimeException("IllegalArgumentException not thrown");
} catch (IllegalArgumentException x) {
}
// UnsupportedOperationException
try {
- dir.register(watcher, new WatchEvent.Kind<?>[]{
+ dir.register(watcher,
new WatchEvent.Kind<Object>() {
@Override public String name() { return "custom"; }
@Override public Class<Object> type() { return Object.class; }
- }});
+ });
+ throw new RuntimeException("UnsupportedOperationException not thrown");
} catch (UnsupportedOperationException x) {
}
try {
@@ -328,7 +335,7 @@
// NullPointerException
System.out.println("NullPointerException tests...");
try {
- dir.register(null, new WatchEvent.Kind<?>[]{ ENTRY_CREATE });
+ dir.register(null, ENTRY_CREATE);
throw new RuntimeException("NullPointerException not thrown");
} catch (NullPointerException x) {
}
@@ -380,7 +387,7 @@
try {
dir.register(watcher, new WatchEvent.Kind<?>[]{ ENTRY_CREATE });
- throw new RuntimeException("ClosedWatchServiceException not thrown");
+ throw new RuntimeException("ClosedWatchServiceException not thrown");
} catch (ClosedWatchServiceException x) {
}
@@ -468,6 +475,28 @@
}
}
+ /**
+ * Test that thread interruped status is preserved upon a call
+ * to register()
+ */
+ static void testThreadInterrupt(Path dir) throws IOException {
+ System.out.println("-- Thread interrupted status test --");
+
+ FileSystem fs = FileSystems.getDefault();
+ Thread curr = Thread.currentThread();
+ try (WatchService watcher = fs.newWatchService()) {
+ System.out.println("interrupting current thread");
+ curr.interrupt();
+ dir.register(watcher, ENTRY_CREATE);
+ if (!curr.isInterrupted())
+ throw new RuntimeException("thread should remain interrupted");
+ System.out.println("current thread is still interrupted");
+ System.out.println("OKAY");
+ } finally {
+ curr.interrupted();
+ }
+ }
+
public static void main(String[] args) throws IOException {
Path dir = TestUtil.createTemporaryDirectory();
try {
@@ -478,6 +507,7 @@
testWakeup(dir);
testExceptions(dir);
testTwoWatchers(dir);
+ testThreadInterrupt(dir);
} finally {
TestUtil.removeAll(dir);
--- a/jdk/test/java/util/BitSet/BSMethods.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/java/util/BitSet/BSMethods.java Mon May 12 09:37:50 2014 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2005, 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
@@ -23,7 +23,7 @@
/* @test
* @bug 4098239 4107540 4080736 4261102 4274710 4305272
- * 4979017 4979028 4979031 5030267 6222207
+ * 4979017 4979028 4979031 5030267 6222207 8040806
* @summary Test the operation of the methods of BitSet class
* @author Mike McCloskey, Martin Buchholz
*/
@@ -897,6 +897,16 @@
private static void testToString() {
check(new BitSet().toString().equals("{}"));
check(makeSet(2,3,42,43,234).toString().equals("{2, 3, 42, 43, 234}"));
+ try {
+ check(makeSet(Integer.MAX_VALUE-1).toString().equals(
+ "{" + (Integer.MAX_VALUE-1) + "}"));
+ check(makeSet(Integer.MAX_VALUE).toString().equals(
+ "{" + Integer.MAX_VALUE + "}"));
+ check(makeSet(0, 1, Integer.MAX_VALUE-1, Integer.MAX_VALUE).toString().equals(
+ "{0, 1, " + (Integer.MAX_VALUE-1) + ", " + Integer.MAX_VALUE + "}"));
+ } catch (IndexOutOfBoundsException exc) {
+ fail("toString() with indices near MAX_VALUE");
+ }
}
private static void testLogicalIdentities() {
--- a/jdk/test/java/util/Locale/Bug7069824.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/java/util/Locale/Bug7069824.java Mon May 12 09:37:50 2014 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 7069824
+ * @bug 7069824 8042360
* @summary Verify implementation for Locale matching.
* @run main Bug7069824
*/
@@ -91,6 +91,17 @@
String range;
double weight;
+ // Testcase for 8042360
+ range = "en-Latn-1234567890";
+ try {
+ lr = new LanguageRange(range);
+ error = true;
+ System.err.println(" IAE should be thrown for LanguageRange("
+ + range + ").");
+ }
+ catch (IllegalArgumentException ex) {
+ }
+
range = null;
try {
lr = new LanguageRange(range);
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java Mon May 12 09:37:50 2014 -0700
@@ -26,6 +26,9 @@
import java.util.*;
import java.util.Spliterators;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.*;
@@ -122,24 +125,33 @@
@Test(groups = { "serialization-hostile" })
public void testSequentialShortCircuitTerminal() {
- // The sorted op for sequential evaluation will buffer all elements when accepting
- // then at the end sort those elements and push those elements downstream
+ // The sorted op for sequential evaluation will buffer all elements when
+ // accepting then at the end sort those elements and push those elements
+ // downstream
+ // A peek operation is added in-between the sorted() and terminal
+ // operation that counts the number of calls to its consumer and
+ // asserts that the number of calls is at most the required quantity
List<Integer> l = Arrays.asList(5, 4, 3, 2, 1);
+ Function<Integer, Stream<Integer>> knownSize = i -> assertNCallsOnly(
+ l.stream().sorted(), Stream::peek, i);
+ Function<Integer, Stream<Integer>> unknownSize = i -> assertNCallsOnly
+ (unknownSizeStream(l).sorted(), Stream::peek, i);
+
// Find
- assertEquals(l.stream().sorted().findFirst(), Optional.of(1));
- assertEquals(l.stream().sorted().findAny(), Optional.of(1));
- assertEquals(unknownSizeStream(l).sorted().findFirst(), Optional.of(1));
- assertEquals(unknownSizeStream(l).sorted().findAny(), Optional.of(1));
+ assertEquals(knownSize.apply(1).findFirst(), Optional.of(1));
+ assertEquals(knownSize.apply(1).findAny(), Optional.of(1));
+ assertEquals(unknownSize.apply(1).findFirst(), Optional.of(1));
+ assertEquals(unknownSize.apply(1).findAny(), Optional.of(1));
// Match
- assertEquals(l.stream().sorted().anyMatch(i -> i == 2), true);
- assertEquals(l.stream().sorted().noneMatch(i -> i == 2), false);
- assertEquals(l.stream().sorted().allMatch(i -> i == 2), false);
- assertEquals(unknownSizeStream(l).sorted().anyMatch(i -> i == 2), true);
- assertEquals(unknownSizeStream(l).sorted().noneMatch(i -> i == 2), false);
- assertEquals(unknownSizeStream(l).sorted().allMatch(i -> i == 2), false);
+ assertEquals(knownSize.apply(2).anyMatch(i -> i == 2), true);
+ assertEquals(knownSize.apply(2).noneMatch(i -> i == 2), false);
+ assertEquals(knownSize.apply(2).allMatch(i -> i == 2), false);
+ assertEquals(unknownSize.apply(2).anyMatch(i -> i == 2), true);
+ assertEquals(unknownSize.apply(2).noneMatch(i -> i == 2), false);
+ assertEquals(unknownSize.apply(2).allMatch(i -> i == 2), false);
}
private <T> Stream<T> unknownSizeStream(List<T> l) {
@@ -199,19 +211,24 @@
public void testIntSequentialShortCircuitTerminal() {
int[] a = new int[]{5, 4, 3, 2, 1};
+ Function<Integer, IntStream> knownSize = i -> assertNCallsOnly(
+ Arrays.stream(a).sorted(), (s, c) -> s.peek(c::accept), i);
+ Function<Integer, IntStream> unknownSize = i -> assertNCallsOnly
+ (unknownSizeIntStream(a).sorted(), (s, c) -> s.peek(c::accept), i);
+
// Find
- assertEquals(Arrays.stream(a).sorted().findFirst(), OptionalInt.of(1));
- assertEquals(Arrays.stream(a).sorted().findAny(), OptionalInt.of(1));
- assertEquals(unknownSizeIntStream(a).sorted().findFirst(), OptionalInt.of(1));
- assertEquals(unknownSizeIntStream(a).sorted().findAny(), OptionalInt.of(1));
+ assertEquals(knownSize.apply(1).findFirst(), OptionalInt.of(1));
+ assertEquals(knownSize.apply(1).findAny(), OptionalInt.of(1));
+ assertEquals(unknownSize.apply(1).findFirst(), OptionalInt.of(1));
+ assertEquals(unknownSize.apply(1).findAny(), OptionalInt.of(1));
// Match
- assertEquals(Arrays.stream(a).sorted().anyMatch(i -> i == 2), true);
- assertEquals(Arrays.stream(a).sorted().noneMatch(i -> i == 2), false);
- assertEquals(Arrays.stream(a).sorted().allMatch(i -> i == 2), false);
- assertEquals(unknownSizeIntStream(a).sorted().anyMatch(i -> i == 2), true);
- assertEquals(unknownSizeIntStream(a).sorted().noneMatch(i -> i == 2), false);
- assertEquals(unknownSizeIntStream(a).sorted().allMatch(i -> i == 2), false);
+ assertEquals(knownSize.apply(2).anyMatch(i -> i == 2), true);
+ assertEquals(knownSize.apply(2).noneMatch(i -> i == 2), false);
+ assertEquals(knownSize.apply(2).allMatch(i -> i == 2), false);
+ assertEquals(unknownSize.apply(2).anyMatch(i -> i == 2), true);
+ assertEquals(unknownSize.apply(2).noneMatch(i -> i == 2), false);
+ assertEquals(unknownSize.apply(2).allMatch(i -> i == 2), false);
}
private IntStream unknownSizeIntStream(int[] a) {
@@ -242,19 +259,24 @@
public void testLongSequentialShortCircuitTerminal() {
long[] a = new long[]{5, 4, 3, 2, 1};
+ Function<Integer, LongStream> knownSize = i -> assertNCallsOnly(
+ Arrays.stream(a).sorted(), (s, c) -> s.peek(c::accept), i);
+ Function<Integer, LongStream> unknownSize = i -> assertNCallsOnly
+ (unknownSizeLongStream(a).sorted(), (s, c) -> s.peek(c::accept), i);
+
// Find
- assertEquals(Arrays.stream(a).sorted().findFirst(), OptionalLong.of(1));
- assertEquals(Arrays.stream(a).sorted().findAny(), OptionalLong.of(1));
- assertEquals(unknownSizeLongStream(a).sorted().findFirst(), OptionalLong.of(1));
- assertEquals(unknownSizeLongStream(a).sorted().findAny(), OptionalLong.of(1));
+ assertEquals(knownSize.apply(1).findFirst(), OptionalLong.of(1));
+ assertEquals(knownSize.apply(1).findAny(), OptionalLong.of(1));
+ assertEquals(unknownSize.apply(1).findFirst(), OptionalLong.of(1));
+ assertEquals(unknownSize.apply(1).findAny(), OptionalLong.of(1));
// Match
- assertEquals(Arrays.stream(a).sorted().anyMatch(i -> i == 2), true);
- assertEquals(Arrays.stream(a).sorted().noneMatch(i -> i == 2), false);
- assertEquals(Arrays.stream(a).sorted().allMatch(i -> i == 2), false);
- assertEquals(unknownSizeLongStream(a).sorted().anyMatch(i -> i == 2), true);
- assertEquals(unknownSizeLongStream(a).sorted().noneMatch(i -> i == 2), false);
- assertEquals(unknownSizeLongStream(a).sorted().allMatch(i -> i == 2), false);
+ assertEquals(knownSize.apply(2).anyMatch(i -> i == 2), true);
+ assertEquals(knownSize.apply(2).noneMatch(i -> i == 2), false);
+ assertEquals(knownSize.apply(2).allMatch(i -> i == 2), false);
+ assertEquals(unknownSize.apply(2).anyMatch(i -> i == 2), true);
+ assertEquals(unknownSize.apply(2).noneMatch(i -> i == 2), false);
+ assertEquals(unknownSize.apply(2).allMatch(i -> i == 2), false);
}
private LongStream unknownSizeLongStream(long[] a) {
@@ -285,19 +307,24 @@
public void testDoubleSequentialShortCircuitTerminal() {
double[] a = new double[]{5.0, 4.0, 3.0, 2.0, 1.0};
+ Function<Integer, DoubleStream> knownSize = i -> assertNCallsOnly(
+ Arrays.stream(a).sorted(), (s, c) -> s.peek(c::accept), i);
+ Function<Integer, DoubleStream> unknownSize = i -> assertNCallsOnly
+ (unknownSizeDoubleStream(a).sorted(), (s, c) -> s.peek(c::accept), i);
+
// Find
- assertEquals(Arrays.stream(a).sorted().findFirst(), OptionalDouble.of(1));
- assertEquals(Arrays.stream(a).sorted().findAny(), OptionalDouble.of(1));
- assertEquals(unknownSizeDoubleStream(a).sorted().findFirst(), OptionalDouble.of(1));
- assertEquals(unknownSizeDoubleStream(a).sorted().findAny(), OptionalDouble.of(1));
+ assertEquals(knownSize.apply(1).findFirst(), OptionalDouble.of(1));
+ assertEquals(knownSize.apply(1).findAny(), OptionalDouble.of(1));
+ assertEquals(unknownSize.apply(1).findFirst(), OptionalDouble.of(1));
+ assertEquals(unknownSize.apply(1).findAny(), OptionalDouble.of(1));
// Match
- assertEquals(Arrays.stream(a).sorted().anyMatch(i -> i == 2.0), true);
- assertEquals(Arrays.stream(a).sorted().noneMatch(i -> i == 2.0), false);
- assertEquals(Arrays.stream(a).sorted().allMatch(i -> i == 2.0), false);
- assertEquals(unknownSizeDoubleStream(a).sorted().anyMatch(i -> i == 2.0), true);
- assertEquals(unknownSizeDoubleStream(a).sorted().noneMatch(i -> i == 2.0), false);
- assertEquals(unknownSizeDoubleStream(a).sorted().allMatch(i -> i == 2.0), false);
+ assertEquals(knownSize.apply(2).anyMatch(i -> i == 2.0), true);
+ assertEquals(knownSize.apply(2).noneMatch(i -> i == 2.0), false);
+ assertEquals(knownSize.apply(2).allMatch(i -> i == 2.0), false);
+ assertEquals(unknownSize.apply(2).anyMatch(i -> i == 2.0), true);
+ assertEquals(unknownSize.apply(2).noneMatch(i -> i == 2.0), false);
+ assertEquals(unknownSize.apply(2).allMatch(i -> i == 2.0), false);
}
private DoubleStream unknownSizeDoubleStream(double[] a) {
@@ -321,4 +348,14 @@
assertSorted(result);
assertContentsUnordered(data, result);
}
+
+ /**
+ * Interpose a consumer that asserts it is called at most N times.
+ */
+ <T, S extends BaseStream<T, S>, R> S assertNCallsOnly(S s, BiFunction<S, Consumer<T>, S> pf, int n) {
+ AtomicInteger boxedInt = new AtomicInteger();
+ return pf.apply(s, i -> {
+ assertFalse(boxedInt.incrementAndGet() > n, "Intermediate op called more than " + n + " time(s)");
+ });
+ }
}
--- a/jdk/test/javax/management/monitor/CounterMonitorDeadlockTest.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/javax/management/monitor/CounterMonitorDeadlockTest.java Mon May 12 09:37:50 2014 -0700
@@ -98,13 +98,13 @@
monitorProxy.start();
final int initGetCount = observedProxy.getGetCount();
- int getCount = initGetCount;
- for (int i = 0; i < 500; i++) { // 500 * 10 = 5 seconds
- getCount = observedProxy.getGetCount();
- if (getCount != initGetCount)
- break;
- Thread.sleep(10);
- }
+ int getCount;
+ System.out.println("Checking GetCount, possible deadlock if timeout.");
+ do { // 8038322. Until timeout of testing harness
+ Thread.sleep(200);
+ } while ((getCount=observedProxy.getGetCount()) == initGetCount);
+ System.out.println("Done!");
+
if (getCount <= initGetCount)
throw new Exception("Test failed: presumable deadlock");
// This won't show up as a deadlock in CTRL-\ or in
@@ -131,10 +131,11 @@
};
mbs.addNotificationListener(monitorName, listener, null, null);
observedProxy.setThing(1000);
- for (int i = 0; i < 500 && notifCount.get() == 0; i++)
- Thread.sleep(10);
- if (notifCount.get() == 0)
- throw new Exception("Test failed: presumable deadlock");
+ System.out.println("Waiting notifCount.get() != 0, possible deadlock if timeout.");
+ do {
+ Thread.sleep(200);
+ } while(notifCount.get() == 0); // 8038322. Until timeout of testing harness
+ System.out.println("Done");
}
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/net/ssl/SSLEngine/IllegalRecordVersion.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,77 @@
+/*
+ * 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.
+ */
+
+// This test case relies on updated static security property, no way to re-use
+// security property in samevm/agentvm mode.
+
+/*
+ * @test
+ * @bug 8042449
+ * @summary Issue for negative byte major record version
+ *
+ * @run main/othervm IllegalRecordVersion
+ */
+
+import javax.net.ssl.*;
+import javax.net.ssl.SSLEngineResult.*;
+import java.io.*;
+import java.security.*;
+import java.nio.*;
+
+public class IllegalRecordVersion {
+
+ public static void main(String args[]) throws Exception {
+ SSLContext context = SSLContext.getDefault();
+
+ SSLEngine cliEngine = context.createSSLEngine();
+ cliEngine.setUseClientMode(true);
+ SSLEngine srvEngine = context.createSSLEngine();
+ srvEngine.setUseClientMode(false);
+
+ SSLSession session = cliEngine.getSession();
+ int netBufferMax = session.getPacketBufferSize();
+ int appBufferMax = session.getApplicationBufferSize();
+
+ ByteBuffer cliToSrv = ByteBuffer.allocateDirect(netBufferMax);
+ ByteBuffer srvIBuff = ByteBuffer.allocateDirect(appBufferMax + 50);
+ ByteBuffer cliOBuff = ByteBuffer.wrap("I'm client".getBytes());
+
+
+ System.out.println("client hello (record version(0xa9, 0xa2))");
+ SSLEngineResult cliRes = cliEngine.wrap(cliOBuff, cliToSrv);
+ System.out.println("Client wrap result: " + cliRes);
+ cliToSrv.flip();
+ if (cliToSrv.limit() > 5) {
+ cliToSrv.put(1, (byte)0xa9);
+ cliToSrv.put(2, (byte)0xa2);
+ }
+
+ try {
+ srvEngine.unwrap(cliToSrv, srvIBuff);
+ throw new Exception(
+ "Cannot catch the unsupported record version issue");
+ } catch (SSLException e) {
+ // get the expected exception
+ }
+ }
+}
--- a/jdk/test/javax/xml/crypto/dsig/GenerationTests.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/javax/xml/crypto/dsig/GenerationTests.java Mon May 12 09:37:50 2014 -0700
@@ -23,7 +23,7 @@
/**
* @test
- * @bug 4635230 6283345 6303830 6824440 6867348 7094155 8038184
+ * @bug 4635230 6283345 6303830 6824440 6867348 7094155 8038184 8038349
* @summary Basic unit tests for generating XML Signatures with JSR 105
* @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java
* X509KeySelector.java GenerationTests.java
@@ -80,9 +80,10 @@
private static KeyInfoFactory kifac;
private static DocumentBuilder db;
private static CanonicalizationMethod withoutComments;
- private static SignatureMethod dsaSha1, rsaSha1, rsaSha256, rsaSha384, rsaSha512;
+ private static SignatureMethod dsaSha1, dsaSha256, rsaSha1,
+ rsaSha256, rsaSha384, rsaSha512;
private static DigestMethod sha1, sha256, sha384, sha512;
- private static KeyInfo dsa, rsa, rsa1024;
+ private static KeyInfo dsa1024, dsa2048, rsa, rsa1024;
private static KeySelector kvks = new KeySelectors.KeyValueKeySelector();
private static KeySelector sks;
private static Key signingKey;
@@ -106,10 +107,13 @@
"http://www.w3.org/TR/xml-stylesheet";
private final static String STYLESHEET_B64 =
"http://www.w3.org/Signature/2002/04/xml-stylesheet.b64";
+ private final static String DSA_SHA256 =
+ "http://www.w3.org/2009/xmldsig11#dsa-sha256";
public static void main(String args[]) throws Exception {
setup();
- test_create_signature_enveloped_dsa();
+ test_create_signature_enveloped_dsa(1024);
+ test_create_signature_enveloped_dsa(2048);
test_create_signature_enveloping_b64_dsa();
test_create_signature_enveloping_dsa();
test_create_signature_enveloping_hmac_sha1_40();
@@ -157,15 +161,18 @@
withoutComments = fac.newCanonicalizationMethod
(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null);
dsaSha1 = fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
+ dsaSha256 = fac.newSignatureMethod(DSA_SHA256, null);
sha1 = fac.newDigestMethod(DigestMethod.SHA1, null);
sha256 = fac.newDigestMethod(DigestMethod.SHA256, null);
sha384 = fac.newDigestMethod
("http://www.w3.org/2001/04/xmldsig-more#sha384", null);
sha512 = fac.newDigestMethod(DigestMethod.SHA512, null);
- dsa = kifac.newKeyInfo(Collections.singletonList
+ dsa1024 = kifac.newKeyInfo(Collections.singletonList
(kifac.newKeyValue(validatingKey)));
+ dsa2048 = kifac.newKeyInfo(Collections.singletonList
+ (kifac.newKeyValue(getPublicKey("DSA", 2048))));
rsa = kifac.newKeyInfo(Collections.singletonList
- (kifac.newKeyValue(getPublicKey("RSA"))));
+ (kifac.newKeyValue(getPublicKey("RSA", 512))));
rsa1024 = kifac.newKeyInfo(Collections.singletonList
(kifac.newKeyValue(getPublicKey("RSA", 1024))));
rsaSha1 = fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
@@ -180,11 +187,25 @@
httpUd = new HttpURIDereferencer();
}
- static void test_create_signature_enveloped_dsa() throws Exception {
- System.out.println("* Generating signature-enveloped-dsa.xml");
+ static void test_create_signature_enveloped_dsa(int size) throws Exception {
+ System.out.println("* Generating signature-enveloped-dsa-"
+ + size + ".xml");
+ SignatureMethod sm = null;
+ KeyInfo ki = null;
+ Key privKey;
+ if (size == 1024) {
+ sm = dsaSha1;
+ ki = dsa1024;
+ privKey = signingKey;
+ } else if (size == 2048) {
+ sm = dsaSha256;
+ ki = dsa2048;
+ privKey = getPrivateKey("DSA", 2048);
+ } else throw new RuntimeException("unsupported keysize:" + size);
+
// create SignedInfo
SignedInfo si = fac.newSignedInfo
- (withoutComments, dsaSha1, Collections.singletonList
+ (withoutComments, sm, Collections.singletonList
(fac.newReference
("", sha1, Collections.singletonList
(fac.newTransform(Transform.ENVELOPED,
@@ -192,7 +213,7 @@
null, null)));
// create XMLSignature
- XMLSignature sig = fac.newXMLSignature(si, dsa);
+ XMLSignature sig = fac.newXMLSignature(si, ki);
Document doc = db.newDocument();
Element envelope = doc.createElementNS
@@ -201,12 +222,12 @@
"xmlns", "http://example.org/envelope");
doc.appendChild(envelope);
- DOMSignContext dsc = new DOMSignContext(signingKey, envelope);
+ DOMSignContext dsc = new DOMSignContext(privKey, envelope);
sig.sign(dsc);
-// StringWriter sw = new StringWriter();
-// dumpDocument(doc, sw);
-// System.out.println(sw.toString());
+// StringWriter sw = new StringWriter();
+// dumpDocument(doc, sw);
+// System.out.println(sw.toString());
DOMValidateContext dvc = new DOMValidateContext
(kvks, envelope.getFirstChild());
@@ -226,21 +247,21 @@
static void test_create_signature_enveloping_b64_dsa() throws Exception {
System.out.println("* Generating signature-enveloping-b64-dsa.xml");
test_create_signature_enveloping
- (sha1, dsaSha1, dsa, signingKey, kvks, true);
+ (sha1, dsaSha1, dsa1024, signingKey, kvks, true);
System.out.println();
}
static void test_create_signature_enveloping_dsa() throws Exception {
System.out.println("* Generating signature-enveloping-dsa.xml");
test_create_signature_enveloping
- (sha1, dsaSha1, dsa, signingKey, kvks, false);
+ (sha1, dsaSha1, dsa1024, signingKey, kvks, false);
System.out.println();
}
static void test_create_signature_enveloping_sha256_dsa() throws Exception {
System.out.println("* Generating signature-enveloping-sha256-dsa.xml");
test_create_signature_enveloping
- (sha256, dsaSha1, dsa, signingKey, kvks, false);
+ (sha256, dsaSha1, dsa1024, signingKey, kvks, false);
System.out.println();
}
@@ -293,7 +314,7 @@
static void test_create_signature_enveloping_rsa() throws Exception {
System.out.println("* Generating signature-enveloping-rsa.xml");
test_create_signature_enveloping(sha1, rsaSha1, rsa,
- getPrivateKey("RSA"), kvks, false);
+ getPrivateKey("RSA", 512), kvks, false);
System.out.println();
}
@@ -301,7 +322,7 @@
throws Exception {
System.out.println("* Generating signature-enveloping-sha384-rsa_sha256.xml");
test_create_signature_enveloping(sha384, rsaSha256, rsa,
- getPrivateKey("RSA"), kvks, false);
+ getPrivateKey("RSA", 512), kvks, false);
System.out.println();
}
@@ -323,13 +344,13 @@
static void test_create_signature_external_b64_dsa() throws Exception {
System.out.println("* Generating signature-external-b64-dsa.xml");
- test_create_signature_external(dsaSha1, dsa, signingKey, kvks, true);
+ test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, true);
System.out.println();
}
static void test_create_signature_external_dsa() throws Exception {
System.out.println("* Generating signature-external-dsa.xml");
- test_create_signature_external(dsaSha1, dsa, signingKey, kvks, false);
+ test_create_signature_external(dsaSha1, dsa1024, signingKey, kvks, false);
System.out.println();
}
@@ -441,7 +462,7 @@
// create XMLSignature
XMLSignature sig = fac.newXMLSignature(si, rsa, objs, "signature", null);
- DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA"), doc);
+ DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
sig.sign(dsc);
@@ -487,7 +508,7 @@
XMLSignature sig = fac.newXMLSignature(si, rsa,
Collections.singletonList(obj),
"signature", null);
- DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA"), doc);
+ DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
dsc.setIdAttributeNS(nc, null, "Id");
sig.sign(dsc);
@@ -530,7 +551,7 @@
XMLSignature sig = fac.newXMLSignature(si, rsa,
Collections.singletonList(obj),
"signature", null);
- DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA"), doc);
+ DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
sig.sign(dsc);
}
@@ -1116,6 +1137,16 @@
"90670890367185141189796";
private static final String DSA_X =
"0527140396812450214498055937934275626078768840117";
+ private static final String DSA_2048_Y =
+ "15119007057343785981993995134621348945077524760182795513668325877793414638620983617627033248732235626178802906346261435991040697338468329634416089753032362617771631199351767336660070462291411472735835843440140283101463231807789628656218830720378705090795271104661936237385140354825159080766174663596286149653433914842868551355716015585570827642835307073681358328172009941968323702291677280809277843998510864653406122348712345584706761165794179850728091522094227603562280855104749858249588234915206290448353957550635709520273178475097150818955098638774564910092913714625772708285992586894795017709678223469405896699928";
+ private static final String DSA_2048_P =
+ "18111848663142005571178770624881214696591339256823507023544605891411707081617152319519180201250440615163700426054396403795303435564101919053459832890139496933938670005799610981765220283775567361483662648340339405220348871308593627647076689407931875483406244310337925809427432681864623551598136302441690546585427193224254314088256212718983105131138772434658820375111735710449331518776858786793875865418124429269409118756812841019074631004956409706877081612616347900606555802111224022921017725537417047242635829949739109274666495826205002104010355456981211025738812433088757102520562459649777989718122219159982614304359";
+ private static final String DSA_2048_Q =
+ "19689526866605154788513693571065914024068069442724893395618704484701";
+ private static final String DSA_2048_G =
+ "2859278237642201956931085611015389087970918161297522023542900348087718063098423976428252369340967506010054236052095950169272612831491902295835660747775572934757474194739347115870723217560530672532404847508798651915566434553729839971841903983916294692452760249019857108409189016993380919900231322610083060784269299257074905043636029708121288037909739559605347853174853410208334242027740275688698461842637641566056165699733710043802697192696426360843173620679214131951400148855611740858610821913573088059404459364892373027492936037789337011875710759208498486908611261954026964574111219599568903257472567764789616958430";
+ private static final String DSA_2048_X =
+ "14562787764977288900757387442281559936279834964901963465277698843172";
private static final String RSA_MOD =
"010800185049102889923150759252557522305032794699952150943573164381" +
"936603255999071981574575044810461362008102247767482738822150129277" +
@@ -1138,43 +1169,48 @@
"204903524890556839550490384015324575598723478554854070823335021842" +
"210112348400928769";
- private static PublicKey getPublicKey(String algo) throws Exception {
- return getPublicKey(algo, 512);
- }
-
private static PublicKey getPublicKey(String algo, int keysize)
throws Exception {
KeyFactory kf = KeyFactory.getInstance(algo);
KeySpec kspec;
if (algo.equalsIgnoreCase("DSA")) {
- kspec = new DSAPublicKeySpec(new BigInteger(DSA_Y),
- new BigInteger(DSA_P),
- new BigInteger(DSA_Q),
- new BigInteger(DSA_G));
+ if (keysize == 1024) {
+ kspec = new DSAPublicKeySpec(new BigInteger(DSA_Y),
+ new BigInteger(DSA_P),
+ new BigInteger(DSA_Q),
+ new BigInteger(DSA_G));
+ } else if (keysize == 2048) {
+ kspec = new DSAPublicKeySpec(new BigInteger(DSA_2048_Y),
+ new BigInteger(DSA_2048_P),
+ new BigInteger(DSA_2048_Q),
+ new BigInteger(DSA_2048_G));
+ } else throw new RuntimeException("Unsupported keysize:" + keysize);
} else if (algo.equalsIgnoreCase("RSA")) {
if (keysize == 512) {
kspec = new RSAPublicKeySpec(new BigInteger(RSA_MOD),
new BigInteger(RSA_PUB));
- } else {
+ } else if (keysize == 1024) {
kspec = new RSAPublicKeySpec(new BigInteger(RSA_1024_MOD),
new BigInteger(RSA_PUB));
- }
+ } else throw new RuntimeException("Unsupported keysize:" + keysize);
} else throw new RuntimeException("Unsupported key algorithm " + algo);
return kf.generatePublic(kspec);
}
- private static PrivateKey getPrivateKey(String algo) throws Exception {
- return getPrivateKey(algo, 512);
- }
-
private static PrivateKey getPrivateKey(String algo, int keysize)
throws Exception {
KeyFactory kf = KeyFactory.getInstance(algo);
KeySpec kspec;
if (algo.equalsIgnoreCase("DSA")) {
- kspec = new DSAPrivateKeySpec
- (new BigInteger(DSA_X), new BigInteger(DSA_P),
- new BigInteger(DSA_Q), new BigInteger(DSA_G));
+ if (keysize == 1024) {
+ kspec = new DSAPrivateKeySpec
+ (new BigInteger(DSA_X), new BigInteger(DSA_P),
+ new BigInteger(DSA_Q), new BigInteger(DSA_G));
+ } else if (keysize == 2048) {
+ kspec = new DSAPrivateKeySpec
+ (new BigInteger(DSA_2048_X), new BigInteger(DSA_2048_P),
+ new BigInteger(DSA_2048_Q), new BigInteger(DSA_2048_G));
+ } else throw new RuntimeException("Unsupported keysize:" + keysize);
} else if (algo.equalsIgnoreCase("RSA")) {
if (keysize == 512) {
kspec = new RSAPrivateKeySpec
--- a/jdk/test/javax/xml/crypto/dsig/KeySelectors.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/javax/xml/crypto/dsig/KeySelectors.java Mon May 12 09:37:50 2014 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2012, 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
@@ -175,7 +175,8 @@
//@@@FIXME: this should also work for key types other than DSA/RSA
static boolean algEquals(String algURI, String algName) {
if (algName.equalsIgnoreCase("DSA") &&
- algURI.equals(SignatureMethod.DSA_SHA1)) {
+ algURI.equals(SignatureMethod.DSA_SHA1) ||
+ algURI.equals("http://www.w3.org/2009/xmldsig11#dsa-sha256")) {
return true;
} else if (algName.equalsIgnoreCase("RSA") &&
(algURI.equals(SignatureMethod.RSA_SHA1) ||
--- a/jdk/test/sun/security/krb5/auto/ReplayCacheTestProc.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/sun/security/krb5/auto/ReplayCacheTestProc.java Mon May 12 09:37:50 2014 -0700
@@ -39,6 +39,8 @@
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.util.*;
+
+import com.sun.security.auth.module.UnixSystem;
import sun.security.jgss.GSSUtil;
import sun.security.krb5.internal.APReq;
import sun.security.krb5.internal.rcache.AuthTime;
@@ -59,7 +61,7 @@
System.getProperty("user.dir");
- private static int uid;
+ private static long uid;
public static void main0(String[] args) throws Exception {
System.setProperty("java.security.krb5.conf", OneKDC.KRB5_CONF);
@@ -78,11 +80,10 @@
}
try {
- Class<?> clazz = Class.forName(
- "com.sun.security.auth.module.UnixSystem");
- uid = (int)(long)(Long)
- clazz.getMethod("getUid").invoke(clazz.newInstance());
- } catch (Exception e) {
+ UnixSystem us = new com.sun.security.auth.module.UnixSystem();
+ uid = us.getUid();
+ } catch (Throwable e) {
+ // Cannot be only Exception, might be UnsatisfiedLinkError
uid = -1;
}
--- a/jdk/test/tools/launcher/FXLauncherTest.java Mon May 05 12:48:07 2014 -0700
+++ b/jdk/test/tools/launcher/FXLauncherTest.java Mon May 12 09:37:50 2014 -0700
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 8001533 8004547
+ * @bug 8001533 8004547 8035782
* @summary Test launching FX application with java -jar
* Test uses main method and blank main method, a jfx app class and an incorrest
* jfx app class, a main-class for the manifest, a bogus one and none.
@@ -373,6 +373,11 @@
System.out.println(tr);
throw new Exception("jfxrt.jar is being loaded, it should not be!");
}
+ if (!tr.notContains("sun.launcher.LauncherHelper$FXHelper")) {
+ System.out.println("testing for extraneous 'sun.launcher.LauncherHelper$FXHelper'");
+ System.out.println(tr);
+ throw new Exception("FXHelper is being loaded, it should not be!");
+ }
for (String p : APP_PARMS) {
if (!tr.contains(p)) {
System.err.println("ERROR: Did not find "
--- a/langtools/.hgtags Mon May 05 12:48:07 2014 -0700
+++ b/langtools/.hgtags Mon May 12 09:37:50 2014 -0700
@@ -254,3 +254,4 @@
2d13524486b46a0f879361fbadf68fe42d02d221 jdk9-b09
7736a820af6f15cef9a1499f122e40abc83b2fbd jdk9-b10
f04fccfbd880c819affc3ef33e0083aab9556409 jdk9-b11
+72efbe612e494f98b9c3ede1b4a3d02304e1e9cc jdk9-b12
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ClassUseWriter.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ClassUseWriter.java Mon May 12 09:37:50 2014 -0700
@@ -180,7 +180,7 @@
Map<String,List<ProgramElementDoc>> map = new HashMap<>();
List<? extends ProgramElementDoc> list= classMap.get(classdoc.qualifiedName());
if (list != null) {
- list.sort(Util.makeComparatorForClassUse());
+ Collections.sort(list, Util.makeComparatorForClassUse());
for (ProgramElementDoc doc : list) {
PackageDoc pkg = doc.containingPackage();
pkgSet.add(pkg);
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/IndexBuilder.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/IndexBuilder.java Mon May 12 09:37:50 2014 -0700
@@ -112,7 +112,7 @@
*/
protected void sortIndexMap() {
for (List<Doc> docs : indexmap.values()) {
- docs.sort(Util.makeComparatorForIndexUse());
+ Collections.sort(docs, Util.makeComparatorForIndexUse());
}
}
--- a/langtools/src/share/classes/com/sun/tools/javac/code/Symbol.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/Symbol.java Mon May 12 09:37:50 2014 -0700
@@ -694,10 +694,10 @@
}
/**
- * A total ordering between type symbols that refines the
+ * A partial ordering between type symbols that refines the
* class inheritance graph.
*
- * Typevariables always precede other kinds of symbols.
+ * Type variables always precede other kinds of symbols.
*/
public final boolean precedes(TypeSymbol that, Types types) {
if (this == that)
--- a/langtools/src/share/classes/com/sun/tools/javac/code/Type.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/Type.java Mon May 12 09:37:50 2014 -0700
@@ -1446,11 +1446,19 @@
*/
public enum InferenceBound {
/** upper bounds */
- UPPER,
+ UPPER {
+ public InferenceBound complement() { return LOWER; }
+ },
/** lower bounds */
- LOWER,
+ LOWER {
+ public InferenceBound complement() { return UPPER; }
+ },
/** equality constraints */
- EQ
+ EQ {
+ public InferenceBound complement() { return EQ; }
+ };
+
+ public abstract InferenceBound complement();
}
/** inference variable bounds */
@@ -1636,6 +1644,9 @@
//only change bounds if request comes from substBounds
super.addBound(ib, bound, types, update);
}
+ else if (bound.hasTag(UNDETVAR) && !((UndetVar) bound).isCaptured()) {
+ ((UndetVar) bound).addBound(ib.complement(), this, types, false);
+ }
}
@Override
--- a/langtools/src/share/classes/com/sun/tools/javac/code/Types.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/Types.java Mon May 12 09:37:50 2014 -0700
@@ -151,31 +151,31 @@
};
// </editor-fold>
- // <editor-fold defaultstate="collapsed" desc="lowerBound">
+ // <editor-fold defaultstate="collapsed" desc="wildLowerBound">
/**
- * The "lvalue conversion".<br>
- * The lower bound of most types is the type
- * itself. Wildcards, on the other hand have upper
- * and lower bounds.
- * @param t a type
- * @return the lower bound of the given type
+ * Get a wildcard's lower bound, returning non-wildcards unchanged.
+ * @param t a type argument, either a wildcard or a type
*/
- public Type lowerBound(Type t) {
- return lowerBound.visit(t);
+ public Type wildLowerBound(Type t) {
+ if (t.hasTag(WILDCARD)) {
+ WildcardType w = (WildcardType) t;
+ return w.isExtendsBound() ? syms.botType : wildLowerBound(w.type);
+ }
+ else return t;
}
- // where
- private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
-
- @Override
- public Type visitWildcardType(WildcardType t, Void ignored) {
- return t.isExtendsBound() ? syms.botType : visit(t.type);
- }
-
- @Override
- public Type visitCapturedType(CapturedType t, Void ignored) {
- return visit(t.getLowerBound());
- }
- };
+ // </editor-fold>
+
+ // <editor-fold defaultstate="collapsed" desc="cvarLowerBound">
+ /**
+ * Get a capture variable's lower bound, returning other types unchanged.
+ * @param t a type
+ */
+ public Type cvarLowerBound(Type t) {
+ if (t.hasTag(TYPEVAR) && ((TypeVar) t).isCaptured()) {
+ return cvarLowerBound(t.getLowerBound());
+ }
+ else return t;
+ }
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="isUnbounded">
@@ -827,9 +827,14 @@
return true;
}
- Type lower = lowerBound(s);
- if (s != lower)
- return isSubtype(capture ? capture(t) : t, lower, false);
+ // Generally, if 's' is a type variable, recur on lower bound; but
+ // for alpha <: CAP, alpha should get upper bound CAP
+ if (!t.hasTag(UNDETVAR)) {
+ // TODO: JDK-8039198, bounds checking sometimes passes in a wildcard as s
+ Type lower = cvarLowerBound(wildLowerBound(s));
+ if (s != lower)
+ return isSubtype(capture ? capture(t) : t, lower, false);
+ }
return isSubtype.visit(capture ? capture(t) : t, s);
}
@@ -1136,7 +1141,7 @@
return visit(s, t);
if (s.isSuperBound() && !s.isExtendsBound())
- return visit(t, upperBound(s)) && visit(t, lowerBound(s));
+ return visit(t, upperBound(s)) && visit(t, wildLowerBound(s));
if (t.isCompound() && s.isCompound()) {
if (!visit(supertype(t), supertype(s)))
@@ -1291,7 +1296,7 @@
break;
}
case SUPER: {
- Type bound = lowerBound(s);
+ Type bound = wildLowerBound(s);
undetvar.addBound(InferenceBound.LOWER, bound, this);
break;
}
@@ -1384,9 +1389,9 @@
// t.isSuperBound()
// || isSubtypeNoCapture(upperBound(s), U(t)));
// System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
-// L(t), t, s, lowerBound(s),
+// L(t), t, s, wildLowerBound(s),
// t.isExtendsBound()
-// || isSubtypeNoCapture(L(t), lowerBound(s)));
+// || isSubtypeNoCapture(L(t), wildLowerBound(s)));
// System.err.println();
// }
@@ -1398,7 +1403,7 @@
// debugContainsType(t, s);
return isSameWildcard(t, s)
|| isCaptureOf(s, t)
- || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
+ || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), wildLowerBound(s))) &&
(t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
}
}
@@ -1760,7 +1765,7 @@
if (s.isExtendsBound())
return !isCastableRecursive(t.type, upperBound(s));
else if (s.isSuperBound())
- return notSoftSubtypeRecursive(lowerBound(s), t.type);
+ return notSoftSubtypeRecursive(wildLowerBound(s), t.type);
} else if (t.isSuperBound()) {
if (s.isExtendsBound())
return notSoftSubtypeRecursive(t.type, upperBound(s));
@@ -1770,19 +1775,13 @@
};
// </editor-fold>
- // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
- /**
- * Returns the lower bounds of the formals of a method.
- */
- public List<Type> lowerBoundArgtypes(Type t) {
- return lowerBounds(t.getParameterTypes());
+ // <editor-fold defaultstate="collapsed" desc="cvarLowerBounds">
+ public List<Type> cvarLowerBounds(List<Type> ts) {
+ return map(ts, cvarLowerBoundMapping);
}
- public List<Type> lowerBounds(List<Type> ts) {
- return map(ts, lowerBoundMapping);
- }
- private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
+ private final Mapping cvarLowerBoundMapping = new Mapping("cvarLowerBound") {
public Type apply(Type t) {
- return lowerBound(t);
+ return cvarLowerBound(t);
}
};
// </editor-fold>
@@ -2251,7 +2250,8 @@
// <editor-fold defaultstate="collapsed" desc="makeCompoundType">
/**
- * Make a compound type from non-empty list of types
+ * Make a compound type from non-empty list of types. The list should be
+ * ordered according to {@link Symbol#precedes(TypeSymbol,Types)}.
*
* @param bounds the types from which the compound type is formed
* @param supertype is objectType if all bounds are interfaces,
@@ -3340,12 +3340,15 @@
* Insert a type in a closure
*/
public List<Type> insert(List<Type> cl, Type t) {
- if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
+ if (cl.isEmpty()) {
return cl.prepend(t);
- } else if (cl.head.tsym.precedes(t.tsym, this)) {
+ } else if (t.tsym == cl.head.tsym) {
+ return cl;
+ } else if (t.tsym.precedes(cl.head.tsym, this)) {
+ return cl.prepend(t);
+ } else {
+ // t comes after head, or the two are unrelated
return insert(cl.tail, t).prepend(cl.head);
- } else {
- return cl;
}
}
@@ -3357,12 +3360,15 @@
return cl2;
} else if (cl2.isEmpty()) {
return cl1;
+ } else if (cl1.head.tsym == cl2.head.tsym) {
+ return union(cl1.tail, cl2.tail).prepend(cl1.head);
} else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
return union(cl1.tail, cl2).prepend(cl1.head);
} else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
return union(cl1, cl2.tail).prepend(cl2.head);
} else {
- return union(cl1.tail, cl2.tail).prepend(cl1.head);
+ // unrelated types
+ return union(cl1.tail, cl2).prepend(cl1.head);
}
}
@@ -3472,18 +3478,31 @@
private List<Type> closureMin(List<Type> cl) {
ListBuffer<Type> classes = new ListBuffer<>();
ListBuffer<Type> interfaces = new ListBuffer<>();
+ Set<Type> toSkip = new HashSet<>();
while (!cl.isEmpty()) {
Type current = cl.head;
- if (current.isInterface())
- interfaces.append(current);
- else
- classes.append(current);
- ListBuffer<Type> candidates = new ListBuffer<>();
- for (Type t : cl.tail) {
- if (!isSubtypeNoCapture(current, t))
- candidates.append(t);
+ boolean keep = !toSkip.contains(current);
+ if (keep && current.hasTag(TYPEVAR)) {
+ // skip lower-bounded variables with a subtype in cl.tail
+ for (Type t : cl.tail) {
+ if (isSubtypeNoCapture(t, current)) {
+ keep = false;
+ break;
+ }
+ }
}
- cl = candidates.toList();
+ if (keep) {
+ if (current.isInterface())
+ interfaces.append(current);
+ else
+ classes.append(current);
+ for (Type t : cl.tail) {
+ // skip supertypes of 'current' in cl.tail
+ if (isSubtypeNoCapture(current, t))
+ toSkip.add(t);
+ }
+ }
+ cl = cl.tail;
}
return classes.appendList(interfaces).toList();
}
@@ -3643,7 +3662,19 @@
return s;
List<Type> closure = union(closure(t), closure(s));
- List<Type> bounds = closureMin(closure);
+ return glbFlattened(closure, t);
+ }
+ //where
+ /**
+ * Perform glb for a list of non-primitive, non-error, non-compound types;
+ * redundant elements are removed. Bounds should be ordered according to
+ * {@link Symbol#precedes(TypeSymbol,Types)}.
+ *
+ * @param flatBounds List of type to glb
+ * @param errT Original type to use if the result is an error type
+ */
+ private Type glbFlattened(List<Type> flatBounds, Type errT) {
+ List<Type> bounds = closureMin(flatBounds);
if (bounds.isEmpty()) { // length == 0
return syms.objectType;
@@ -3651,11 +3682,21 @@
return bounds.head;
} else { // length > 1
int classCount = 0;
- for (Type bound : bounds)
- if (!bound.isInterface())
+ List<Type> lowers = List.nil();
+ for (Type bound : bounds) {
+ if (!bound.isInterface()) {
classCount++;
- if (classCount > 1)
- return createErrorType(t);
+ Type lower = cvarLowerBound(bound);
+ if (bound != lower && !lower.hasTag(BOT))
+ lowers = insert(lowers, lower);
+ }
+ }
+ if (classCount > 1) {
+ if (lowers.isEmpty())
+ return createErrorType(errT);
+ else
+ return glbFlattened(union(bounds, lowers), errT);
+ }
}
return makeCompoundType(bounds);
}
@@ -3929,8 +3970,13 @@
Si.lower = Ti.getSuperBound();
break;
}
- if (Si.bound == Si.lower)
+ Type tmpBound = Si.bound.hasTag(UNDETVAR) ? ((UndetVar)Si.bound).qtype : Si.bound;
+ Type tmpLower = Si.lower.hasTag(UNDETVAR) ? ((UndetVar)Si.lower).qtype : Si.lower;
+ if (!Si.bound.hasTag(ERROR) &&
+ !Si.lower.hasTag(ERROR) &&
+ isSameType(tmpBound, tmpLower, false)) {
currentS.head = Si.bound;
+ }
}
currentA = currentA.tail;
currentT = currentT.tail;
@@ -4135,7 +4181,7 @@
if (source.isExtendsBound())
adaptRecursive(upperBound(source), upperBound(target));
else if (source.isSuperBound())
- adaptRecursive(lowerBound(source), lowerBound(target));
+ adaptRecursive(wildLowerBound(source), wildLowerBound(target));
return null;
}
@@ -4147,7 +4193,7 @@
Type val = mapping.get(source.tsym);
if (val != null) {
if (val.isSuperBound() && target.isSuperBound()) {
- val = isSubtype(lowerBound(val), lowerBound(target))
+ val = isSubtype(wildLowerBound(val), wildLowerBound(target))
? target : val;
} else if (val.isExtendsBound() && target.isExtendsBound()) {
val = isSubtype(upperBound(val), upperBound(target))
@@ -4261,7 +4307,7 @@
}
public Type visitType(Type t, Void s) {
- return high ? upperBound(t) : lowerBound(t);
+ return high ? upperBound(t) : t;
}
@Override
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java Mon May 12 09:37:50 2014 -0700
@@ -3214,6 +3214,14 @@
result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
}
+ /** Report dependencies.
+ * @param from The enclosing class sym
+ * @param to The found identifier that the class depends on.
+ */
+ public void reportDependence(Symbol from, Symbol to) {
+ // Override if you want to collect the reported dependencies.
+ }
+
public void visitSelect(JCFieldAccess tree) {
// Determine the expected kind of the qualifier expression.
int skind = 0;
@@ -3341,6 +3349,10 @@
env.info.selectSuper = selectSuperPrev;
result = checkId(tree, site, sym, env, resultInfo);
+
+ if ((tree.sym.kind & TYP) != 0) {
+ reportDependence(env.enclClass.sym, tree.sym);
+ }
}
//where
/** Determine symbol referenced by a Select expression,
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java Mon May 12 09:37:50 2014 -0700
@@ -626,7 +626,7 @@
} else if (a.isExtendsBound()) {
return types.isCastable(bound, types.upperBound(a), types.noWarnings);
} else if (a.isSuperBound()) {
- return !types.notSoftSubtype(types.lowerBound(a), bound);
+ return !types.notSoftSubtype(types.wildLowerBound(a), bound);
}
return true;
}
@@ -2730,7 +2730,7 @@
if (types.isSameType(type, syms.stringType)) return;
if ((type.tsym.flags() & Flags.ENUM) != 0) return;
if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
- if (types.lowerBound(type).tsym == syms.classType.tsym) return;
+ if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return;
if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
validateAnnotationType(pos, types.elemtype(type));
return;
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java Mon May 12 09:37:50 2014 -0700
@@ -1458,7 +1458,7 @@
Type solve(UndetVar uv, InferenceContext inferenceContext) {
Infer infer = inferenceContext.infer();
List<Type> hibounds = filterBounds(uv, inferenceContext);
- //note: lobounds should have at least one element
+ //note: hibounds should have at least one element
Type owntype = hibounds.tail.tail == null ? hibounds.head : infer.types.glb(hibounds);
if (owntype.isPrimitive() || owntype.hasTag(ERROR)) {
throw infer.inferenceException
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java Mon May 12 09:37:50 2014 -0700
@@ -1552,7 +1552,7 @@
currentResolutionContext.methodCheck =
prevResolutionContext.methodCheck.mostSpecificCheck(actuals, !allowBoxing);
Type mst = instantiate(env, site, m2, null,
- adjustArgs(types.lowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
+ adjustArgs(types.cvarLowerBounds(types.memberType(site, m1).getParameterTypes()), m1, maxLength, useVarargs), null,
allowBoxing, useVarargs, noteWarner);
return mst != null &&
!noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java Mon May 12 09:37:50 2014 -0700
@@ -131,6 +131,12 @@
public boolean preferSource;
/**
+ * Switch: Search classpath and sourcepath for classes before the
+ * bootclasspath
+ */
+ public boolean userPathsFirst;
+
+ /**
* The currently selected profile.
*/
public final Profile profile;
@@ -270,6 +276,7 @@
saveParameterNames = options.isSet("save-parameter-names");
cacheCompletionFailure = options.isUnset("dev");
preferSource = "source".equals(options.get("-Xprefer"));
+ userPathsFirst = options.isSet(XXUSERPATHSFIRST);
profile = Profile.instance(context);
@@ -2649,7 +2656,7 @@
if (c.owner == p) // it might be an inner class
p.members_field.enter(c);
}
- } else if (c.classfile != null && (c.flags_field & seen) == 0) {
+ } else if (!preferCurrent && c.classfile != null && (c.flags_field & seen) == 0) {
// if c.classfile == null, we are currently compiling this class
// and no further action is necessary.
// if (c.flags_field & seen) != 0, we have already encountered
@@ -2695,19 +2702,32 @@
private boolean verbosePath = true;
+ // Set to true when the currently selected file should be kept
+ private boolean preferCurrent;
+
/** Load directory of package into members scope.
*/
private void fillIn(PackageSymbol p) throws IOException {
- if (p.members_field == null) p.members_field = new Scope(p);
- String packageName = p.fullname.toString();
-
- Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
+ if (p.members_field == null)
+ p.members_field = new Scope(p);
- fillIn(p, PLATFORM_CLASS_PATH,
- fileManager.list(PLATFORM_CLASS_PATH,
- packageName,
- EnumSet.of(JavaFileObject.Kind.CLASS),
- false));
+ preferCurrent = false;
+ if (userPathsFirst) {
+ scanUserPaths(p);
+ preferCurrent = true;
+ scanPlatformPath(p);
+ } else {
+ scanPlatformPath(p);
+ scanUserPaths(p);
+ }
+ verbosePath = false;
+ }
+
+ /**
+ * Scans class path and source path for files in given package.
+ */
+ private void scanUserPaths(PackageSymbol p) throws IOException {
+ Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
classKinds.remove(JavaFileObject.Kind.SOURCE);
@@ -2748,6 +2768,7 @@
}
}
+ String packageName = p.fullname.toString();
if (wantSourceFiles && !haveSourcePath) {
fillIn(p, CLASS_PATH,
fileManager.list(CLASS_PATH,
@@ -2768,7 +2789,17 @@
sourceKinds,
false));
}
- verbosePath = false;
+ }
+
+ /**
+ * Scans platform class path for files in given package.
+ */
+ private void scanPlatformPath(PackageSymbol p) throws IOException {
+ fillIn(p, PLATFORM_CLASS_PATH,
+ fileManager.list(PLATFORM_CLASS_PATH,
+ p.fullname.toString(),
+ EnumSet.of(JavaFileObject.Kind.CLASS),
+ false));
}
// where
private void fillIn(PackageSymbol p,
--- a/langtools/src/share/classes/com/sun/tools/javac/main/Option.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/main/Option.java Mon May 12 09:37:50 2014 -0700
@@ -416,6 +416,8 @@
XPREFER("-Xprefer:", "opt.prefer", EXTENDED, BASIC, ONEOF, "source", "newer"),
+ XXUSERPATHSFIRST("-XXuserPathsFirst", "opt.userpathsfirst", HIDDEN, BASIC),
+
// see enum PkgInfo
XPKGINFO("-Xpkginfo:", "opt.pkginfo", EXTENDED, BASIC, ONEOF, "always", "legacy", "nonempty"),
--- a/langtools/src/share/classes/com/sun/tools/javac/resources/javac.properties Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/resources/javac.properties Mon May 12 09:37:50 2014 -0700
@@ -240,6 +240,8 @@
Print information about rounds of annotation processing
javac.opt.printProcessorInfo=\
Print information about which annotations a processor is asked to process
+javac.opt.userpathsfirst=\
+ Search classpath and sourcepath for classes before the bootclasspath instead of after
javac.opt.prefer=\
Specify which file to read when both a source file and class file are found for an implicitly compiled class
javac.opt.AT=\
--- a/langtools/src/share/classes/com/sun/tools/sjavac/Source.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/sjavac/Source.java Mon May 12 09:37:50 2014 -0700
@@ -313,7 +313,7 @@
int sp = fn.lastIndexOf(File.separatorChar);
String pkg = "";
if (sp != -1) {
- pkg = fn.substring(0,sp);
+ pkg = fn.substring(0,sp).replace('/','.');
}
// Is this a module-info.java file?
if (fn.endsWith("module-info.java")) {
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/sjavac/comp/AttrWithDeps.java Mon May 12 09:37:50 2014 -0700
@@ -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. 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.sjavac.comp;
+
+import com.sun.tools.javac.comp.Attr;
+import com.sun.tools.javac.util.Context;
+import com.sun.tools.javac.code.Symbol;
+
+/** Subclass to Attr that overrides reportDepedence.
+ *
+ * <p><b>This is NOT part of any supported API.
+ * If you write code that depends on this, you do so at your own
+ * risk. This code and its internal interfaces are subject to change
+ * or deletion without notice.</b></p>
+ */
+public class AttrWithDeps extends Attr {
+
+ /** The dependency database
+ */
+ protected Dependencies deps;
+
+ protected AttrWithDeps(Context context) {
+ super(context);
+ deps = Dependencies.instance(context);
+ }
+
+ public static void preRegister(Context context) {
+ context.put(attrKey, new Context.Factory<Attr>() {
+ public Attr make(Context c) {
+ Attr instance = new AttrWithDeps(c);
+ c.put(Attr.class, instance);
+ return instance;
+ }
+ });
+ }
+
+ /** Collect dependencies in the enclosing class
+ * @param from The enclosing class sym
+ * @param to The enclosing classes references this sym.
+ * */
+ @Override
+ public void reportDependence(Symbol from, Symbol to) {
+ // Capture dependencies between the packages.
+ deps.collect(from.packge().fullname, to.packge().fullname);
+ }
+}
--- a/langtools/src/share/classes/com/sun/tools/sjavac/server/CompilerThread.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/src/share/classes/com/sun/tools/sjavac/server/CompilerThread.java Mon May 12 09:37:50 2014 -0700
@@ -51,6 +51,7 @@
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.BaseFileManager;
import com.sun.tools.javac.util.StringUtils;
+import com.sun.tools.sjavac.comp.AttrWithDeps;
import com.sun.tools.sjavac.comp.Dependencies;
import com.sun.tools.sjavac.comp.JavaCompilerWithDeps;
import com.sun.tools.sjavac.comp.SmartFileManager;
@@ -131,6 +132,7 @@
context = new Context();
context.put(JavaFileManager.class, smartFileManager);
ResolveWithDeps.preRegister(context);
+ AttrWithDeps.preRegister(context);
JavaCompilerWithDeps.preRegister(context, this);
subTasks = new ArrayList<>();
}
--- a/langtools/test/tools/javac/annotations/typeAnnotations/failures/CantAnnotatePackages.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/test/tools/javac/annotations/typeAnnotations/failures/CantAnnotatePackages.java Mon May 12 09:37:50 2014 -0700
@@ -1,6 +1,6 @@
/*
* @test /nodynamiccopyright/
- * @bug 1234567
+ * @bug 8026564
* @summary The parts of a fully-qualified type can't be annotated.
* @author Werner Dietl
* @compile/fail/ref=CantAnnotatePackages.out -XDrawDiagnostics CantAnnotatePackages.java
--- a/langtools/test/tools/javac/annotations/typeAnnotations/failures/TypeVariableMissingTA.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/test/tools/javac/annotations/typeAnnotations/failures/TypeVariableMissingTA.java Mon May 12 09:37:50 2014 -0700
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 1234567
+ * @bug 8026564
* @summary A missing annotation type in a type variable bound
* should result in the same errors with and without an
* annotation processor.
--- a/langtools/test/tools/javac/annotations/typeAnnotations/failures/common/arrays/DeclarationAnnotation.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/test/tools/javac/annotations/typeAnnotations/failures/common/arrays/DeclarationAnnotation.java Mon May 12 09:37:50 2014 -0700
@@ -1,6 +1,6 @@
/*
* @test /nodynamiccopyright/
- * @bug 1234567
+ * @bug 8013852
* @summary ensure that declaration annotations are not allowed on
* new array expressions
* @author Werner Dietl
--- a/langtools/test/tools/javac/annotations/typeAnnotations/failures/common/receiver/DeclarationAnnotation.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/test/tools/javac/annotations/typeAnnotations/failures/common/receiver/DeclarationAnnotation.java Mon May 12 09:37:50 2014 -0700
@@ -1,6 +1,6 @@
/*
* @test /nodynamiccopyright/
- * @bug 1234567
+ * @bug 8013852
* @summary ensure that declaration annotations are not allowed on
* method receiver types
* @author Werner Dietl
--- a/langtools/test/tools/javac/annotations/typeAnnotations/failures/common/wildcards/DeclarationAnnotation.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/test/tools/javac/annotations/typeAnnotations/failures/common/wildcards/DeclarationAnnotation.java Mon May 12 09:37:50 2014 -0700
@@ -1,6 +1,6 @@
/*
* @test /nodynamiccopyright/
- * @bug 1234567
+ * @bug 8013852
* @summary ensure that declaration annotations are not allowed on
* wildcards
* @author Werner Dietl
--- a/langtools/test/tools/javac/annotations/typeAnnotations/newlocations/AnonymousClass.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/test/tools/javac/annotations/typeAnnotations/newlocations/AnonymousClass.java Mon May 12 09:37:50 2014 -0700
@@ -25,7 +25,7 @@
/*
* @test
- * @bug 1234567
+ * @bug 8013852
* @summary new type annotation location: anonymous class creation
* @author Werner Dietl
* @compile AnonymousClass.java
--- a/langtools/test/tools/javac/annotations/typeAnnotations/referenceinfos/Initializers.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/test/tools/javac/annotations/typeAnnotations/referenceinfos/Initializers.java Mon May 12 09:37:50 2014 -0700
@@ -25,7 +25,7 @@
/*
* @test
- * @bug 1234567
+ * @bug 8013852
* @summary Test population of reference info for instance and class initializers
* @author Werner Dietl
* @compile -g Driver.java ReferenceInfoUtil.java Initializers.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/classfiles/attributes/SourceFile/AnonymousClassTest.java Mon May 12 09:37:50 2014 -0700
@@ -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
+ * @summary sourcefile attribute test for anonymous class.
+ * @bug 8040129
+ * @library /tools/javac/lib ../lib
+ * @build SourceFileTestBase TestBase InMemoryFileManager ToolBox
+ * @run main AnonymousClassTest
+ */
+
+public class AnonymousClassTest extends SourceFileTestBase {
+ public static void main(String[] args) throws Exception {
+ new AnonymousClassTest().test(new Object(){}.getClass(), "AnonymousClassTest.java");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/classfiles/attributes/SourceFile/InnerClassTest.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,40 @@
+/*
+ * 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 sourcefile attribute test for inner class.
+ * @bug 8040129
+ * @library /tools/javac/lib ../lib
+ * @build SourceFileTestBase TestBase InMemoryFileManager ToolBox
+ * @run main InnerClassTest
+ */
+
+public class InnerClassTest extends SourceFileTestBase {
+ public static void main(String[] args) throws Exception {
+ new InnerClassTest().test(Inner.class, "InnerClassTest.java");
+ }
+
+ class Inner {
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/classfiles/attributes/SourceFile/LocalClassTest.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,39 @@
+/*
+ * 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 sourcefile attribute test for local class.
+ * @bug 8040129
+ * @library /tools/javac/lib ../lib
+ * @build SourceFileTestBase TestBase InMemoryFileManager ToolBox
+ * @run main LocalClassTest
+ */
+
+public class LocalClassTest extends SourceFileTestBase {
+ public static void main(String[] args) throws Exception {
+ class Local {
+ }
+ new LocalClassTest().test(Local.class, "LocalClassTest.java");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/classfiles/attributes/SourceFile/MixTest.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,83 @@
+/*
+ * 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 sourcefile attribute test for complex structure of nested classes and other types.
+ * @bug 8040129
+ * @library /tools/javac/lib ../lib
+ * @build SourceFileTestBase TestBase InMemoryFileManager ToolBox
+ * @run main MixTest
+ */
+
+public class MixTest extends SourceFileTestBase {
+ public static void main(String[] args) throws Exception {
+ new InnerClass();
+ Runnable r = new Runnable() {
+ @Override
+ public void run() {
+ Runnable run = () -> {
+ class Local {
+ }
+ };
+ }
+
+ class innerInAnonymous {
+ }
+ };
+
+ new MixTest().run();
+ }
+
+ public void run() throws Exception {
+ String fileName = getClass().getName() + ".java";
+ test("MixTest", fileName);
+ test("MixTest$1", fileName);
+ test("MixTest$InnerClass", fileName);
+ test("MixTest$1$innerInAnonymous", fileName);
+ test("MixTest$1$1Local", fileName);
+ test("MixTest$InnerClass$innerEnum", fileName);
+ test("MixTest$InnerClass$innerInterface", fileName);
+ test("MixTest$InnerClass$innerEnum$innerClassInnerEnum", fileName);
+ test("MixTest$InnerClass$innerEnum$innerClassInnerEnum$1InnerLocal", fileName);
+ }
+
+ static class InnerClass {
+ private InnerClass() {
+ }
+
+ enum innerEnum {
+ E;
+
+ class innerClassInnerEnum {
+ void method() {
+ class InnerLocal {
+ }
+ }
+ }
+ }
+
+ @interface innerInterface {
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/classfiles/attributes/SourceFile/NoSourceFileAttribute.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,50 @@
+/*
+ * 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 sourcefile attribute test for file compiled without debug information.
+ * @library /tools/javac/lib ../lib
+ * @build SourceFileTestBase TestBase InMemoryFileManager ToolBox
+ * @compile -g:none NoSourceFileAttribute.java
+ * @run main NoSourceFileAttribute
+ */
+
+import com.sun.tools.classfile.Attribute;
+import com.sun.tools.classfile.ClassFile;
+import com.sun.tools.classfile.ConstantPoolException;
+
+import java.io.IOException;
+
+
+public class NoSourceFileAttribute extends TestBase {
+ public static void main(String[] args) throws Exception {
+ new NoSourceFileAttribute().test();
+ }
+
+ public void test() throws IOException, ConstantPoolException {
+ assertNull(
+ ClassFile.read(getClassFile(NoSourceFileAttribute.class)).getAttribute(Attribute.SourceFile),
+ "Classfile should have no SourceFile attribute when compiled without debug information.");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/classfiles/attributes/SourceFile/SourceFileTestBase.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,76 @@
+/*
+ * 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 com.sun.tools.classfile.Attribute;
+import com.sun.tools.classfile.ClassFile;
+import com.sun.tools.classfile.SourceFile_attribute;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import javax.tools.JavaFileObject;
+
+public class SourceFileTestBase extends TestBase {
+
+ protected void test(Class<?> classToTest, String fileName) throws Exception {
+ assertAttributePresent(ClassFile.read(getClassFile(classToTest)), fileName);
+ }
+
+ protected void test(String classToTest, String fileName) throws Exception {
+ assertAttributePresent(ClassFile.read(getClassFile(classToTest + ".class")), fileName);
+ }
+
+ /**
+ * Compile sourceCode and for all "classesToTest" checks SourceFile attribute.
+ */
+ protected void compileAndTest(String sourceCode, String... classesToTest) throws Exception {
+
+ Map<String, ? extends JavaFileObject> classes = compile(sourceCode);
+ String fileName = ToolBox.getJavaFileNameFromSource(sourceCode);
+ for (String className : classesToTest) {
+ assertAttributePresent(ClassFile.read(classes.get(className).openInputStream()), fileName);
+ }
+ }
+
+ private void assertAttributePresent(ClassFile classFile, String fileName) throws Exception {
+
+ //We need to count attributes with the same names because there is no appropriate API in the ClassFile.
+
+ List<SourceFile_attribute> sourceFileAttributes = new ArrayList<>();
+ for (Attribute a : classFile.attributes.attrs) {
+ if (Attribute.SourceFile.equals(a.getName(classFile.constant_pool))) {
+ sourceFileAttributes.add((SourceFile_attribute) a);
+ }
+ }
+
+ assertEquals(sourceFileAttributes.size(), 1, "Should be the only SourceFile attribute");
+
+ SourceFile_attribute attribute = sourceFileAttributes.get(0);
+
+ assertEquals(classFile.constant_pool.getUTF8Info(attribute.attribute_name_index).value,
+ Attribute.SourceFile, "Incorrect attribute name");
+ assertEquals(classFile.constant_pool.getUTF8Info(attribute.sourcefile_index).value, fileName,
+ "Incorrect source file name");
+ assertEquals(attribute.attribute_length, 2, "Incorrect attribute length");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/classfiles/attributes/SourceFile/SyntheticClassTest.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,44 @@
+/*
+ * 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 sourcefile attribute test for synthetic class.
+ * @bug 8040129
+ * @library /tools/javac/lib ../lib
+ * @build SourceFileTestBase TestBase InMemoryFileManager ToolBox
+ * @run main SyntheticClassTest
+ */
+
+public class SyntheticClassTest extends SourceFileTestBase {
+ public static void main(String[] args) throws Exception {
+ new Inner();
+
+ new SyntheticClassTest().test("SyntheticClassTest$1", "SyntheticClassTest.java");
+ }
+
+ static class Inner {
+ private Inner() {
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/classfiles/attributes/SourceFile/TopLevelClassesOneFileTest.java Mon May 12 09:37:50 2014 -0700
@@ -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.
+ */
+
+/*
+ * @test
+ * @summary sourcefile attribute test for two type in one file.
+ * @bug 8040129
+ * @library /tools/javac/lib ../lib
+ * @build SourceFileTestBase TestBase InMemoryFileManager ToolBox
+ * @run main TopLevelClassesOneFileTest
+ */
+
+public class TopLevelClassesOneFileTest extends SourceFileTestBase {
+ public static void main(String[] args) throws Exception {
+ new TopLevelClassesOneFileTest().run();
+ }
+
+ public void run() throws Exception {
+ int failed = 0;
+ for (Type firstType : Type.values()) {
+ for (Type secondType : Type.values()) {
+ if (firstType != secondType) {
+ try {
+ compileAndTest("public " + firstType.source + secondType.source,
+ firstType.name(), secondType.name());
+ } catch (AssertionFailedException | CompilationException ex) {
+ System.err.println("Failed with public type " + firstType.name()
+ + " and type " + secondType.name());
+ ex.printStackTrace();
+ failed++;
+ }
+ }
+ }
+ }
+ if (failed > 0)
+ throw new AssertionFailedException("Test failed. Failed cases count = " + failed + " .See log.");
+ }
+
+ enum Type {
+ CLASS("class CLASS{}"),
+ INTERFACE("interface INTERFACE{}"),
+ ENUM("enum ENUM{;}"),
+ ANNOTATION("@interface ANNOTATION{}");
+
+ String source;
+
+ Type(String source) {
+ this.source = source;
+ }
+ }
+}
--- a/langtools/test/tools/javac/generics/inference/7086586/T7086586.out Mon May 05 12:48:07 2014 -0700
+++ b/langtools/test/tools/javac/generics/inference/7086586/T7086586.out Mon May 12 09:37:50 2014 -0700
@@ -1,5 +1,5 @@
-T7086586.java:14:20: compiler.err.cant.apply.symbol: kindname.method, m, java.util.List<? super T>, java.util.List<compiler.misc.type.captureof: 1, ?>, kindname.class, T7086586, (compiler.misc.infer.no.conforming.assignment.exists: T, (compiler.misc.inconvertible.types: java.util.List<compiler.misc.type.captureof: 1, ?>, java.util.List<? super T>))
-T7086586.java:15:20: compiler.err.cant.apply.symbol: kindname.method, m, java.util.List<? super T>, java.util.List<compiler.misc.type.captureof: 1, ?>, kindname.class, T7086586, (compiler.misc.infer.no.conforming.assignment.exists: T, (compiler.misc.inconvertible.types: java.util.List<compiler.misc.type.captureof: 1, ?>, java.util.List<? super T>))
-T7086586.java:16:23: compiler.err.cant.apply.symbol: kindname.method, m, java.util.List<? super T>, java.util.List<compiler.misc.type.captureof: 1, ?>, kindname.class, T7086586, (compiler.misc.infer.no.conforming.assignment.exists: T, (compiler.misc.inconvertible.types: java.util.List<compiler.misc.type.captureof: 1, ?>, java.util.List<? super T>))
-T7086586.java:17:9: compiler.err.cant.apply.symbol: kindname.method, m, java.util.List<? super T>, java.util.List<compiler.misc.type.captureof: 1, ?>, kindname.class, T7086586, (compiler.misc.infer.no.conforming.assignment.exists: T, (compiler.misc.inconvertible.types: java.util.List<compiler.misc.type.captureof: 1, ?>, java.util.List<? super T>))
+T7086586.java:14:28: compiler.err.prob.found.req: (compiler.misc.inconvertible.types: compiler.misc.type.captureof: 1, ?, java.lang.String)
+T7086586.java:15:28: compiler.err.prob.found.req: (compiler.misc.inconvertible.types: compiler.misc.type.captureof: 1, ?, java.lang.Number)
+T7086586.java:16:31: compiler.err.prob.found.req: (compiler.misc.inconvertible.types: compiler.misc.type.captureof: 1, ?, java.lang.Exception)
+T7086586.java:17:13: compiler.err.cant.resolve.location.args: kindname.method, nonExistentMethod, , , (compiler.misc.location: kindname.interface, java.util.List<compiler.misc.type.captureof: 1, ?>, null)
4 errors
--- a/langtools/test/tools/javac/generics/inference/7086586/T7086586b.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/test/tools/javac/generics/inference/7086586/T7086586b.java Mon May 12 09:37:50 2014 -0700
@@ -23,9 +23,10 @@
/*
* @test
- * @bug 7086586
+ * @bug 7086586 8033718
*
- * @summary Inference producing null type argument
+ * @summary Inference producing null type argument; inference ignores capture
+ * variable as upper bound
*/
import java.util.List;
@@ -40,8 +41,8 @@
assertionCount++;
}
- <T> void m(List<? super T> dummy) { assertTrue(false); }
- <T> void m(Object dummy) { assertTrue(true); }
+ <T> void m(List<? super T> dummy) { assertTrue(true); }
+ <T> void m(Object dummy) { assertTrue(false); }
void test(List<?> l) {
m(l);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/generics/inference/LowerBoundGLB.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,47 @@
+/*
+ * 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 8033718
+ * @author dlsmith
+ * @summary GLB for two capture variables with lower bounds
+ * @compile LowerBoundGLB.java
+ */
+
+public class LowerBoundGLB {
+
+ interface Box<T> {
+ T get();
+ void set(T arg);
+ }
+
+ <T> T doGLB(Box<? super T> b1, Box<? super T> b2) {
+ return null;
+ }
+
+ void test(Box<? super String> l1, Box<? super CharSequence> l2) {
+ doGLB(l1, l2).substring(3);
+ }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/generics/wildcards/RefQueue.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,24 @@
+/*
+ * 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.
+ */
+
+public class RefQueue<S> { }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/generics/wildcards/RefQueueBug.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,38 @@
+/*
+ * 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 8033437
+ * @summary inconsistent generic types behaviour when compiling together vs. separate
+ * @compile RefQueue.java
+ * @compile RefQueueBug.java
+ */
+
+public class RefQueueBug<T> {
+ final RefQueue<? super T> queue = new RefQueue<>();
+ public static void main(String[] args) {
+ RefQueueBug<Object> r = new RefQueueBug<>();
+ RefQueue<Object> q = r.queue;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/options/xprefer/XPreferTest.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,385 @@
+/*
+ * 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 Tests which path is used to represent an implicit type given
+ * various xprefer arguments and multiple .class / .java files involved.
+ * @bug 8028196
+ */
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
+import java.util.Scanner;
+
+import javax.tools.JavaCompiler;
+import javax.tools.JavaCompiler.CompilationTask;
+import javax.tools.ToolProvider;
+
+
+public class XPreferTest {
+
+ enum Dir {
+ SOURCE_PATH("src"),
+ CLASS_PATH("cp"),
+ BOOT_PATH("boot");
+
+ File file;
+ Dir(String dir) {
+ this.file = new File(dir);
+ }
+ }
+
+ enum ImplicitOption {
+ XPREFER_SOURCE("-Xprefer:source"),
+ XPREFER_NEWER("-Xprefer:newer"),
+ XXUSERPATHSFIRST("-XXuserPathsFirst");
+
+ final String optionString;
+ private ImplicitOption(String optionString) {
+ this.optionString = optionString;
+ }
+ }
+
+ final static JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
+ final static File OUTPUT_DIR = new File("out");
+
+ public static void main(String... args) throws Exception {
+
+ // Initialize test-directories
+ OUTPUT_DIR.mkdir();
+ for (Dir dir : Dir.values())
+ dir.file.mkdir();
+
+ int testCaseCounter = 0;
+
+ for (List<Dir> dirSubset : SubseqIter.subseqsOf(Dir.values())) {
+
+ if (dirSubset.isEmpty())
+ continue;
+
+ for (ImplicitOption policy : ImplicitOption.values()) {
+ for (List<Dir> dirOrder : PermutationIterator.permutationsOf(dirSubset)) {
+ new TestCase(dirOrder, policy, testCaseCounter++).run();
+ }
+ }
+ }
+ }
+
+ static class TestCase {
+
+ String classId;
+ List<Dir> dirs;
+ ImplicitOption option;
+
+ public TestCase(List<Dir> dirs, ImplicitOption option, int testCaseNum) {
+ this.dirs = dirs;
+ this.option = option;
+ this.classId = "XPreferTestImplicit" + testCaseNum;
+ }
+
+ void run() throws Exception {
+
+ System.out.println("Test:");
+ System.out.println(" Class id: " + classId);
+ System.out.println(" Dirs: " + dirs);
+ System.out.println(" Option: " + option);
+
+ createTestFiles();
+ String compileOutput = compile();
+ Dir actual = getChosenOrigin(compileOutput);
+ Dir expected = getExpectedOrigin();
+
+ System.out.println(" Expected: " + expected);
+ System.out.println(" Actual: " + actual);
+
+ if (actual != expected) {
+ throw new RuntimeException(String.format(
+ "Expected javac to choose %s but %s was chosen",
+ expected == null ? "<none>" : expected.name(),
+ actual == null ? "<none>" : actual.name()));
+ }
+ }
+
+ Dir getExpectedOrigin() {
+
+ Dir newest = dirs.get(0);
+
+ switch (option) {
+
+ case XPREFER_NEWER:
+
+ Dir cls = dirs.contains(Dir.BOOT_PATH) ? Dir.BOOT_PATH
+ : dirs.contains(Dir.CLASS_PATH) ? Dir.CLASS_PATH
+ : null;
+
+ Dir src = dirs.contains(Dir.SOURCE_PATH) ? Dir.SOURCE_PATH
+ : null;
+
+ for (Dir dir : dirs)
+ if (dir == cls || dir == src)
+ return dir;
+
+ return null;
+
+ case XPREFER_SOURCE:
+ return dirs.contains(Dir.SOURCE_PATH) ? Dir.SOURCE_PATH
+ : dirs.contains(Dir.BOOT_PATH) ? Dir.BOOT_PATH
+ : dirs.contains(Dir.CLASS_PATH) ? Dir.CLASS_PATH
+ : null;
+
+ case XXUSERPATHSFIRST:
+
+ for (Dir dir : dirs)
+ if (dir == Dir.SOURCE_PATH || dir == Dir.CLASS_PATH)
+ return dir;
+
+ // Neither SOURCE_PATH nor CLASS_PATH among dirs. Safty check:
+ if (newest != Dir.BOOT_PATH)
+ throw new AssertionError("Expected to find BOOT_PATH");
+
+ return Dir.BOOT_PATH;
+
+ default:
+ throw new RuntimeException("Unhandled policy case.");
+ }
+ }
+
+ Dir getChosenOrigin(String compilerOutput) {
+ Scanner s = new Scanner(compilerOutput);
+ while (s.hasNextLine()) {
+ String line = s.nextLine();
+ if (line.matches("\\[loading .*\\]"))
+ for (Dir dir : Dir.values())
+ if (line.contains(dir.file.getName() + "/" + classId))
+ return dir;
+ }
+ return null;
+ }
+
+ String compile() throws IOException {
+
+ // Create a class that references classId
+ File explicit = new File("ExplicitClass.java");
+ FileWriter filewriter = new FileWriter(explicit);
+ filewriter.append("class ExplicitClass { " + classId + " implicit; }");
+ filewriter.close();
+
+ StringWriter sw = new StringWriter();
+
+ com.sun.tools.javac.Main.compile(new String[] {
+ "-verbose",
+ option.optionString,
+ "-sourcepath", Dir.SOURCE_PATH.file.getPath(),
+ "-classpath", Dir.CLASS_PATH.file.getPath(),
+ "-Xbootclasspath/p:" + Dir.BOOT_PATH.file.getPath(),
+ "-d", XPreferTest.OUTPUT_DIR.getPath(),
+ explicit.getPath()
+ }, new PrintWriter(sw));
+
+ return sw.toString();
+ }
+
+ void createTestFiles() throws IOException {
+ long t = 1390927988755L; // Tue Jan 28 17:53:08 CET 2014
+ for (Dir dir : dirs) {
+ createFile(dir).setLastModified(t);
+ t -= 10000;
+ }
+ }
+
+ File createFile(Dir dir) throws IOException {
+ File src = new File(dir.file, classId + ".java");
+ try (FileWriter w = new FileWriter(src)) {
+ w.append("public class " + classId + " {}");
+ }
+ // If we're after the ".java" representation, we're done...
+ if(dir == Dir.SOURCE_PATH)
+ return src;
+ // ...otherwise compile into a ".class".
+ CompilationTask task = comp.getTask(null, null, null, null, null,
+ comp.getStandardFileManager(null, null, null).getJavaFileObjects(src));
+ File dest = new File(dir.file, classId + ".class");
+ if(!task.call() || !dest.exists())
+ throw new RuntimeException("Compilation failure.");
+ src.delete();
+ return dest;
+ }
+ }
+}
+
+// Iterator for iteration over all subsequences of a given list.
+class SubseqIter<T> implements Iterator<List<T>> {
+
+ List<T> elements;
+ boolean[] states;
+
+ public SubseqIter(Collection<T> c) {
+ states = new boolean[c.size()];
+ elements = new ArrayList<T>(c);
+ }
+
+ public static <T> Iterable<List<T>> subseqsOf(final T[] t) {
+ return new Iterable<List<T>>() {
+ @Override
+ public Iterator<List<T>> iterator() {
+ return new SubseqIter<T>(Arrays.asList(t));
+ }
+ };
+ }
+
+ // Roll values in 'states' from index i and forward.
+ // Return true if we wrapped back to zero.
+ private boolean roll(int i) {
+ if (i == states.length)
+ return true;
+ if (!roll(i + 1))
+ return false;
+ states[i] = !states[i];
+ return !states[i];
+ }
+
+ @Override
+ public List<T> next() {
+ if (!hasNext())
+ throw new NoSuchElementException();
+ // Include element i if states[i] is true
+ List<T> next = new ArrayList<T>();
+ for (int i = 0; i < states.length; i++)
+ if (states[i])
+ next.add(elements.get(i));
+ if (roll(0))
+ states = null; // hasNext() == false from now on.
+ return next;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return states != null;
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+}
+
+class PermutationIterator<T> implements Iterator<List<T>> {
+
+ DirInt head;
+ boolean hasNext = true;
+
+ public PermutationIterator(List<T> toPermute) {
+ ListIterator<T> iter = toPermute.listIterator();
+ if (iter.hasNext())
+ head = new DirInt(iter.nextIndex(), iter.next());
+ DirInt prev = head;
+ while (iter.hasNext()) {
+ DirInt di = new DirInt(iter.nextIndex(), iter.next());
+ di.left = prev;
+ prev.right = di;
+ prev = di;
+ }
+ }
+
+ public static <T> Iterable<List<T>> permutationsOf(final List<T> list) {
+ return new Iterable<List<T>>() {
+ public Iterator<List<T>> iterator() {
+ return new PermutationIterator<>(list);
+ }
+ };
+ }
+
+ @Override
+ public boolean hasNext() {
+ return hasNext;
+ }
+
+ @Override
+ public List<T> next() {
+ // Prep return value based on current state
+ List<T> result = new ArrayList<>();
+ for (DirInt di = head; di != null; di = di.right)
+ result.add(di.object);
+
+ // Step state forward
+ DirInt maxMob = null;
+ for (DirInt di = head; di != null; di = di.right)
+ if (di.isMobile() && (maxMob == null || di.val > maxMob.val))
+ maxMob = di;
+
+ if (maxMob == null) {
+ hasNext = false;
+ } else {
+ maxMob.swapWithAdjacent();
+ for (DirInt di = head; di != null; di = di.right)
+ if (di.val > maxMob.val)
+ di.facingLeft = !di.facingLeft;
+ }
+ return result;
+ }
+
+ private final class DirInt {
+ int val;
+ T object;
+ DirInt left, right;
+ boolean facingLeft = true;
+
+ public DirInt(int val, T object) {
+ this.val = val;
+ this.object = object;
+ }
+
+ boolean isMobile() {
+ DirInt adjacent = facingLeft ? left : right;
+ return adjacent != null && val > adjacent.val;
+ }
+
+ public void swapWithAdjacent() {
+ DirInt l = facingLeft ? left : this;
+ DirInt r = facingLeft ? this : right;
+ if (head == l) head = r;
+ if (l.left != null) l.left.right = r;
+ if (r.right != null) r.right.left = l;
+ l.right = r.right;
+ r.left = l.left;
+ r.right = l;
+ l.left = r;
+ }
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+}
--- a/langtools/test/tools/javac/processing/model/type/BasicAnnoTests.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/test/tools/javac/processing/model/type/BasicAnnoTests.java Mon May 12 09:37:50 2014 -0700
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 1234567
+ * @bug 8013852
* @summary Annotations on types
* @library /tools/javac/lib
* @ignore
--- a/langtools/test/tools/sjavac/SJavac.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/test/tools/sjavac/SJavac.java Mon May 12 09:37:50 2014 -0700
@@ -83,6 +83,7 @@
compileWithInvisibleSources();
compileCircularSources();
compileExcludingDependency();
+ incrementalCompileTestFullyQualifiedRef();
delete(gensrc);
delete(gensrc2);
@@ -95,15 +96,15 @@
System.out.println("\nInitial compile of gensrc.");
System.out.println("----------------------------");
populate(gensrc,
- "alfa/AINT.java",
- "package alfa; public interface AINT { void aint(); }",
+ "alfa/omega/AINT.java",
+ "package alfa.omega; public interface AINT { void aint(); }",
- "alfa/A.java",
- "package alfa; public class A implements AINT { "+
+ "alfa/omega/A.java",
+ "package alfa.omega; public class A implements AINT { "+
"public final static int DEFINITION = 17; public void aint() { } }",
- "alfa/AA.java",
- "package alfa;"+
+ "alfa/omega/AA.java",
+ "package alfa.omega;"+
"// A package private class, not contributing to the public api.\n"+
"class AA {"+
" // A properly nested static inner class.\n"+
@@ -127,7 +128,7 @@
"package beta;public interface BINT { void foo(); }",
"beta/B.java",
- "package beta; import alfa.A; public class B {"+
+ "package beta; import alfa.omega.A; public class B {"+
"private int b() { return A.DEFINITION; } native void foo(); }");
compile("gensrc", "-d", "bin", "-h", "headers", "-j", "1",
@@ -151,16 +152,16 @@
System.out.println("\nTesting that deleting AA.java deletes all");
System.out.println("generated inner class as well as AA.class");
System.out.println("-----------------------------------------");
- removeFrom(gensrc, "alfa/AA.java");
+ removeFrom(gensrc, "alfa/omega/AA.java");
compile("gensrc", "-d", "bin", "-h", "headers", "-j", "1",
"--server:portfile=testserver,background=false", "--log=debug");
Map<String,Long> new_bin_state = collectState(bin);
verifyThatFilesHaveBeenRemoved(previous_bin_state, new_bin_state,
- "bin/alfa/AA$1.class",
- "bin/alfa/AA$AAAA.class",
- "bin/alfa/AA$AAA.class",
- "bin/alfa/AAAAA.class",
- "bin/alfa/AA.class");
+ "bin/alfa/omega/AA$1.class",
+ "bin/alfa/omega/AA$AAAA.class",
+ "bin/alfa/omega/AA$AAA.class",
+ "bin/alfa/omega/AAAAA.class",
+ "bin/alfa/omega/AA.class");
previous_bin_state = new_bin_state;
Map<String,Long> new_headers_state = collectState(headers);
@@ -175,8 +176,8 @@
System.out.println("Since we did not modify the native api of B.");
System.out.println("-------------------------------------------------------------");
- populate(gensrc,"alfa/A.java",
- "package alfa; public class A implements AINT { "+
+ populate(gensrc,"alfa/omega/A.java",
+ "package alfa.omega; public class A implements AINT { "+
"public final static int DEFINITION = 18; public void aint() { } private void foo() { } }");
compile("gensrc", "-d", "bin", "-h", "headers", "-j", "1",
@@ -184,8 +185,8 @@
Map<String,Long> new_bin_state = collectState(bin);
verifyNewerFiles(previous_bin_state, new_bin_state,
- "bin/alfa/A.class",
- "bin/alfa/AINT.class",
+ "bin/alfa/omega/A.class",
+ "bin/alfa/omega/AINT.class",
"bin/beta/B.class",
"bin/beta/BINT.class",
"bin/javac_state");
@@ -202,7 +203,7 @@
System.out.println("---------------------------------------------------------");
populate(gensrc,"beta/B.java",
- "package beta; import alfa.A; public class B {"+
+ "package beta; import alfa.omega.A; public class B {"+
"private int b() { return A.DEFINITION; } }");
compile("gensrc", "-d", "bin", "-h", "headers", "-j", "1",
@@ -226,7 +227,7 @@
System.out.println("------------------------------------------------------------------------");
populate(gensrc,"beta/B.java",
- "package beta; import alfa.A; public class B {"+
+ "package beta; import alfa.omega.A; public class B {"+
"private int b() { return A.DEFINITION; } "+
"@java.lang.annotation.Native final static int alfa = 42; }");
@@ -252,7 +253,7 @@
System.out.println("-------------------------------------------------------------------");
populate(gensrc,"beta/B.java",
- "package beta; import alfa.A; public class B {"+
+ "package beta; import alfa.omega.A; public class B {"+
"private int b() { return A.DEFINITION; } "+
"@java.lang.annotation.Native final static int alfa = 43; }");
@@ -282,8 +283,8 @@
delete(bin);
previous_bin_state = collectState(bin);
- populate(gensrc,"alfa/A.java",
- "package alfa; import beta.B; import gamma.C; public class A { B b; C c; }",
+ populate(gensrc,"alfa/omega/A.java",
+ "package alfa.omega; import beta.B; import gamma.C; public class A { B b; C c; }",
"beta/B.java",
"package beta; public class B { broken",
"gamma/C.java",
@@ -297,7 +298,7 @@
"--server:portfile=testserver,background=false");
Map<String,Long> new_bin_state = collectState(bin);
verifyThatFilesHaveBeenAdded(previous_bin_state, new_bin_state,
- "bin/alfa/A.class",
+ "bin/alfa/omega/A.class",
"bin/beta/B.class",
"bin/gamma/C.class",
"bin/javac_state");
@@ -325,8 +326,8 @@
delete(bin);
previous_bin_state = collectState(bin);
- populate(gensrc,"alfa/A.java",
- "package alfa; import beta.B; import gamma.C; public class A { B b; C c; }");
+ populate(gensrc,"alfa/omega/A.java",
+ "package alfa.omega; import beta.B; import gamma.C; public class A { B b; C c; }");
populate(gensrc2,"beta/B.java",
"package beta; public class B { broken",
"gamma/C.java",
@@ -341,7 +342,7 @@
System.out.println("The first compile went well!");
Map<String,Long> new_bin_state = collectState(bin);
verifyThatFilesHaveBeenAdded(previous_bin_state, new_bin_state,
- "bin/alfa/A.class",
+ "bin/alfa/omega/A.class",
"bin/javac_state");
System.out.println("----- Compile with exluded beta went well!");
@@ -365,18 +366,18 @@
delete(bin);
previous_bin_state = collectState(bin);
- populate(gensrc,"alfa/A.java",
- "package alfa; public class A { beta.B b; }",
+ populate(gensrc,"alfa/omega/A.java",
+ "package alfa.omega; public class A { beta.B b; }",
"beta/B.java",
"package beta; public class B { gamma.C c; }",
"gamma/C.java",
- "package gamma; public class C { alfa.A a; }");
+ "package gamma; public class C { alfa.omega.A a; }");
compile("gensrc", "-d", "bin", "-h", "headers", "-j", "3",
"--server:portfile=testserver,background=false","--log=debug");
Map<String,Long> new_bin_state = collectState(bin);
verifyThatFilesHaveBeenAdded(previous_bin_state, new_bin_state,
- "bin/alfa/A.class",
+ "bin/alfa/omega/A.class",
"bin/beta/B.class",
"bin/gamma/C.class",
"bin/javac_state");
@@ -396,20 +397,57 @@
previous_bin_state = collectState(bin);
populate(gensrc,
- "alfa/A.java",
- "package alfa; public class A { beta.B b; }",
+ "alfa/omega/A.java",
+ "package alfa.omega; public class A { beta.B b; }",
"beta/B.java",
"package beta; public class B { }");
- compile("-x", "beta", "-src", "gensrc", "-x", "alfa", "-sourcepath", "gensrc",
+ compile("-x", "beta", "-src", "gensrc", "-x", "alfa/omega", "-sourcepath", "gensrc",
"-d", "bin", "--server:portfile=testserver,background=false");
Map<String,Long> new_bin_state = collectState(bin);
verifyThatFilesHaveBeenAdded(previous_bin_state, new_bin_state,
- "bin/alfa/A.class",
+ "bin/alfa/omega/A.class",
"bin/javac_state");
}
+ void incrementalCompileTestFullyQualifiedRef() throws Exception {
+ System.out.println("Verify that \"alfa.omega.A a;\" does create a proper dependency.");
+ System.out.println("----------------------------------------------------------------");
+
+ populate(gensrc,
+ "alfa/omega/A.java",
+ "package alfa.omega; public class A { "+
+ " public final static int DEFINITION = 18; "+
+ " public void hello() { }"+
+ "}",
+ "beta/B.java",
+ "package beta; public class B { "+
+ " public void world() { alfa.omega.A a; }"+
+ "}");
+
+ compile("gensrc", "-d", "bin", "-j", "1",
+ "--server:portfile=testserver,background=false", "--log=debug");
+ Map<String,Long> previous_bin_state = collectState(bin);
+
+ // Change pubapi of A, this should trigger a recompile of B.
+ populate(gensrc,
+ "alfa/omega/A.java",
+ "package alfa.omega; public class A { "+
+ " public final static int DEFINITION = 19; "+
+ " public void hello() { }"+
+ "}");
+
+ compile("gensrc", "-d", "bin", "-j", "1",
+ "--server:portfile=testserver,background=false", "--log=debug");
+ Map<String,Long> new_bin_state = collectState(bin);
+
+ verifyNewerFiles(previous_bin_state, new_bin_state,
+ "bin/alfa/omega/A.class",
+ "bin/beta/B.class",
+ "bin/javac_state");
+ }
+
void removeFrom(Path dir, String... args) throws IOException {
for (String filename : args) {
Path p = dir.resolve(filename);
--- a/langtools/test/tools/sjavac/SJavacWrapper.java Mon May 05 12:48:07 2014 -0700
+++ b/langtools/test/tools/sjavac/SJavacWrapper.java Mon May 12 09:37:50 2014 -0700
@@ -26,6 +26,8 @@
* @summary Test all aspects of sjavac.
*
* @bug 8004658
+ * @bug 8042441
+ * @bug 8042699
* @summary Add internal smart javac wrapper to solve JEP 139
*
* @run main SJavacWrapper
--- a/make/Javadoc.gmk Mon May 05 12:48:07 2014 -0700
+++ b/make/Javadoc.gmk Mon May 12 09:37:50 2014 -0700
@@ -115,10 +115,7 @@
DOCSDIR_URL = {@docroot}/$(GET2DOCSDIR)
# Url to copyright html file
-COPYRIGHT_URL-7 = $(DOCSDIR_URL)/legal/cpyr.html
-# This isn't added in old build yet.
-#COPYRIGHT_URL-8 = $(DOCSDIR_URL)/legal/cpyr.html
-COPYRIGHT_URL = $(COPYRIGHT_URL-$(JDK_MINOR_VERSION))
+COPYRIGHT_URL = $(DOCSDIR_URL)/legal/cpyr.html
# Url to bug filing site
BUG_SUBMIT_URL = http://bugreport.sun.com/bugreport/
--- a/nashorn/.hgtags Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/.hgtags Mon May 12 09:37:50 2014 -0700
@@ -245,3 +245,4 @@
27f6ea87dcbd52c4b59e34a9f18d5b3321d53fa7 jdk9-b09
0eaa55c7abe5d96023a4b38a326f411209c43f49 jdk9-b10
4d60c3292e14aac90dc3b8232496ba4af4254cc3 jdk9-b11
+282e9a675e079cc84dbfaa4c10050f08397faab0 jdk9-b12
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/BufferArray.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+import jdk.nashorn.api.scripting.AbstractJSObject;
+import java.nio.DoubleBuffer;
+
+/**
+ * Simple class demonstrating pluggable script object
+ * implementation. By implementing jdk.nashorn.api.scripting.JSObject
+ * (or extending AbstractJSObject which implements it), you
+ * can supply a friendly script object. Nashorn will call
+ * 'magic' methods on such a class on 'obj.foo, obj.foo = 33,
+ * obj.bar()' etc. from script.
+ *
+ * In this example, Java nio DoubleBuffer object is wrapped
+ * as a friendly script object that provides indexed acces
+ * to buffer content and also support array-like "length"
+ * readonly property to retrieve buffer's capacity. This class
+ * also demonstrates a function valued property called "buf".
+ * On 'buf' method, we return the underlying nio buffer object
+ * that is being wrapped.
+ */
+public class BufferArray extends AbstractJSObject {
+ // underlying nio buffer
+ private final DoubleBuffer buf;
+
+ public BufferArray(int size) {
+ buf = DoubleBuffer.allocate(size);
+ }
+
+ public BufferArray(DoubleBuffer buf) {
+ this.buf = buf;
+ }
+
+ // called to check if indexed property exists
+ @Override
+ public boolean hasSlot(int index) {
+ return index > 0 && index < buf.capacity();
+ }
+
+ // get the value from that index
+ @Override
+ public Object getSlot(int index) {
+ return buf.get(index);
+ }
+
+ // set the value at that index
+ @Override
+ public void setSlot(int index, Object value) {
+ buf.put(index, ((Number)value).doubleValue());
+ }
+
+ // do you have a property of that given name?
+ @Override
+ public boolean hasMember(String name) {
+ return "length".equals(name) || "buf".equals(name);
+ }
+
+ // get the value of that named property
+ @Override
+ public Object getMember(String name) {
+ switch (name) {
+ case "length":
+ return buf.capacity();
+ case "buf":
+ // return a 'function' value for this property
+ return new AbstractJSObject() {
+ @Override
+ public Object call(Object thiz, Object... args) {
+ return BufferArray.this.buf;
+ }
+
+ // yes, I'm a function !
+ @Override
+ public boolean isFunction() {
+ return true;
+ }
+ };
+ }
+ return null;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/CastExample.java Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Simple java example with type casts.
+// see javacastcounter.js.
+
+class CastExample {
+ public final static int I = (int)23.33;
+ public final String str = (String)"hello";
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/README Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,1 @@
+Simple Nashorn examples that can be run with "jjs" tool.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/array_mapreduce.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Usage: jjs array_mapreduce.js
+
+// Many Array.prototype functions such as map,
+// filter, reduce, reduceRight, every, some are generic.
+// These functions accept ECMAScript array as well as
+// many array-like objects including java arrays.
+// So, you can do map/filter/reduce with Java streams or
+// you can also use Array.prototype functions as below.
+// See also http://en.wikipedia.org/wiki/MapReduce
+
+var DoubleArray = Java.type("double[]");
+var StringArray = Java.type("java.lang.String[]");
+
+var map = Array.prototype.map;
+var filter = Array.prototype.filter;
+var reduce = Array.prototype.reduce;
+
+var jarr = new StringArray(5);
+jarr[0] = "nashorn";
+jarr[1] = "ecmascript";
+jarr[2] = "javascript";
+jarr[3] = "js";
+jarr[4] = "scheme";
+
+// sum of word lengths
+print("Sum word length:",
+ reduce.call(
+ map.call(jarr, function(x) x.length),
+ function(x, y) x + y)
+);
+
+// another array example involving numbers
+jarr = new DoubleArray(10);
+// make random array of numbers
+for (var i = 0; i < jarr.length; i++)
+ jarr[i] = Math.random();
+
+var forEach = Array.prototype.forEach;
+// print numbers in the array
+forEach.call(jarr, function(x) print(x));
+
+// print sum of squares of the random numbers
+print("Square sum:",
+ reduce.call(
+ map.call(jarr, function(x) x*x),
+ function(x, y) x + y)
+);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/astviewer.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,98 @@
+#// Usage: jjs -scripting -fx astviewer.js -- <scriptfile>
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+if (!$OPTIONS._fx) {
+ print("Usage: jjs -scripting -fx astviewer.js -- <.js file>");
+ exit(1);
+}
+
+// Using JavaFX from Nashorn. See also:
+// http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/javafx.html
+
+// This example shows AST of a script file as a JavaFX
+// tree view in a window. If no file is specified, AST of
+// this script file is shown. This script demonstrates
+// 'load' function, JavaFX support by -fx, readFully function
+// in scripting mode.
+
+// JavaFX classes used
+var StackPane = Java.type("javafx.scene.layout.StackPane");
+var Scene = Java.type("javafx.scene.Scene");
+var TreeItem = Java.type("javafx.scene.control.TreeItem");
+var TreeView = Java.type("javafx.scene.control.TreeView");
+
+// Create a javafx TreeItem to view a AST node
+function treeItemForASTNode(ast, name) {
+ var item = new TreeItem(name);
+ for (var prop in ast) {
+ var node = ast[prop];
+ if (typeof node == 'object') {
+ if (node == null) {
+ // skip nulls
+ continue;
+ }
+
+ if (Array.isArray(node) && node.length == 0) {
+ // skip empty arrays
+ continue;
+ }
+
+ var subitem = treeItemForASTNode(node, prop);
+ } else {
+ var subitem = new TreeItem(prop + ": " + node);
+ }
+ item.children.add(subitem);
+ }
+ return item;
+}
+
+// do we have a script file passed? if not, use current script
+var sourceName = arguments.length == 0? __FILE__ : arguments[0];
+
+// load parser.js from nashorn resources
+load("nashorn:parser.js");
+
+// read the full content of the file and parse it
+// to get AST of the script specified
+var ast = parse(readFully(sourceName));
+
+// JavaFX start method
+function start(stage) {
+ stage.title = "AST Viewer";
+ var rootItem = treeItemForASTNode(ast, sourceName);
+ var tree = new TreeView(rootItem);
+ var root = new StackPane();
+ root.children.add(tree);
+ stage.scene = new Scene(root, 300, 450);
+ stage.show();
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/barchart_weather.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,116 @@
+#// Usage: jjs -fx barchart_weather.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Example that retrieves weather data from a URL in JSON
+// format and draws bar chart using JavaFX
+
+// -fx check
+if (! $OPTIONS._fx) {
+ print("Usage: jjs -fx barchart_weather.js");
+ exit(1);
+}
+
+// Java classes used
+var URL = Java.type("java.net.URL");
+var BufferedReader = Java.type("java.io.BufferedReader");
+var InputStreamReader = Java.type("java.io.InputStreamReader");
+
+// function to retrieve text content of the given URL
+function readTextFromURL(url) {
+ var str = '';
+ var u = new URL(url);
+ var reader = new BufferedReader(
+ new InputStreamReader(u.openStream()));
+ try {
+ reader.lines().forEach(function(x) str += x);
+ return str;
+ } finally {
+ reader.close();
+ }
+}
+
+// change URL for your city here!
+var url = "http://api.openweathermap.org/data/2.5/forecast?q=chennai,india&units=metric&mode=json";
+
+// download JSON document and parse
+var json = readTextFromURL(url);
+var weather = JSON.parse(json);
+
+// View JSON of this using site such as http://www.jsoneditoronline.org/ to know
+// about the JSON data format used by this site
+
+// Extracted data from the json object
+var temp = weather.list.map(function(x) x.main.temp);
+var temp_min = weather.list.map(function(x) x.main.temp_min);
+var temp_max = weather.list.map(function(x) x.main.temp_max);
+var date = weather.list.map(function(x) x.dt_txt);
+
+// JavaFX classes used
+var Scene = Java.type("javafx.scene.Scene");
+var BarChart = Java.type("javafx.scene.chart.BarChart");
+var CategoryAxis = Java.type("javafx.scene.chart.CategoryAxis");
+var NumberAxis = Java.type("javafx.scene.chart.NumberAxis");
+var XYChart = Java.type("javafx.scene.chart.XYChart");
+
+function start(stage) {
+ stage.title="Chennai Weather Bar Chart";
+ var xAxis = new CategoryAxis();
+ xAxis.label = "date/time";
+ var yAxis = new NumberAxis();
+ yAxis.label = "temp in C";
+ var bc = new BarChart(xAxis, yAxis);
+
+ // 3 bars per datetime item - temp, min temp and max temp
+ var s1 = new XYChart.Series();
+ s1.name = "temp";
+ for (d in date) {
+ s1.data.add(new XYChart.Data(date[d], temp[d]));
+ }
+
+ var s2 = new XYChart.Series();
+ s2.name = "min temp";
+ for (d in date) {
+ s2.data.add(new XYChart.Data(date[d], temp_min[d]));
+ }
+
+ var s3 = new XYChart.Series();
+ s3.name = "max temp";
+ for (d in date) {
+ s3.data.add(new XYChart.Data(date[d], temp_max[d]));
+ }
+
+ bc.data.addAll(s1, s2, s3);
+
+ stage.scene = new Scene(bc, 800, 600);
+ stage.show();
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/call_lambda.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// nashorn allows you treat every Java8 lambda as a function
+
+var JFunction = Java.type("java.util.function.Function");
+var obj = new JFunction() {
+ apply: function(x) {
+ print(x + ", lambda");
+ }
+};
+
+// prints 'function'
+print(typeof obj);
+
+// call it!
+obj("hello");
--- a/nashorn/samples/counters.js Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/samples/counters.js Mon May 12 09:37:50 2014 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 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
@@ -33,7 +33,11 @@
* This file can be run along with any script you want to run
* to print aggregate stat counters from nashorn.
*
- * Usage: jjs <your-file.js> counters.js
+ * Usage: jjs -J-Dnashorn.debug <your-file.js> counters.js
*/
-Debug.dumpCounters();
+if (java.lang.System.getProperty("nashorn.debug") == null) {
+ print("Usage: jjs -J-Dnashorn.debug <your-file.js> counters.js");
+} else {
+ Debug.dumpCounters();
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/dirname.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// __DIR__ variable is equivalent of `dirname $0` in
+// shell scripts - expands to the directory where
+// the current script is located.
+
+print("This script is in the directory: " + __DIR__);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/disassemble.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Usage: jjs disassemble.js -- <.class-file-path>
+
+// Simple .class disassembler that uses bundled ObjectWeb ASM
+// classes in jdk8. WARNING: Bundled ObjectWeb ASM classes are
+// not part of official jdk8 API. It can be changed/removed
+// without notice. So, this script is brittle by design!
+
+// This example demonstrates passing arguments to script
+// from jjs command line, nio and ASM usage.
+
+// classes used
+var FileSystems = Java.type("java.nio.file.FileSystems");
+var Files = Java.type("java.nio.file.Files");
+var System = Java.type("java.lang.System");
+var PrintWriter = Java.type("java.io.PrintWriter");
+
+// WARNING: uses non-API classes of jdk8!
+var ClassReader = Java.type("jdk.internal.org.objectweb.asm.ClassReader");
+var TraceClassVisitor = Java.type("jdk.internal.org.objectweb.asm.util.TraceClassVisitor");
+
+// convert file name to Path instance
+function path(file) {
+ return FileSystems.default.getPath(file);
+}
+
+// read all file content as a byte[]
+function readAllBytes(file) {
+ return Files.readAllBytes(path(file));
+}
+
+// disassemble .class byte[] and prints output to stdout
+function disassemble(bytecode) {
+ var pw = new PrintWriter(System.out);
+ new ClassReader(bytecode).accept(new TraceClassVisitor(pw), 0);
+}
+
+// check for command line arg (for .class file name)
+if (arguments.length == 0 || !arguments[0].endsWith('.class')) {
+ print("Usage: jjs disassemble -- <.class file>");
+ exit(1);
+}
+
+// disassemble the given .class file
+disassemble(readAllBytes(arguments[0]));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/engine/README Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,1 @@
+Using javax.script engine API of nashorn from script!
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/engine/accessvar.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Simple example showing global variable access from caller
+
+var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
+// create manager
+var manager = new ScriptEngineManager();
+// create engine
+var engine = manager.getEngineByName("js");
+
+// eval code!
+engine.eval("x = 'hello'");
+
+// access global var from engine
+print(engine.get('x'));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/engine/callfunc.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// simple example showing how to call a global script
+// function from caller
+
+var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
+// create manager
+var manager = new ScriptEngineManager();
+// create engine
+var engine = manager.getEngineByName("js");
+
+// eval code!
+engine.eval("function func(name) { print('I am func, hello ' + name) }");
+
+// invoke functions, methods of code evaluated by engine
+// from javax.script.Invocable interface. But, hey,
+// calling code is JavaScript and don't worry about types :)
+
+engine.invokeFunction("func", "Nashorn");
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/engine/callmethod.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,64 @@
+#// Usage: jjs -scripting callmethod.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// simple example demonstrating calling a script object
+// method from script engine user code
+
+var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
+// create manager
+var manager = new ScriptEngineManager();
+// create engine
+var engine = manager.getEngineByName("js");
+
+// eval code - too many script escapes?
+// use heredoc !
+engine.eval(<<CODE
+ var obj = {
+ func: function() {
+ print("I am func of " + this);
+ },
+
+ toString: function() {
+ return "Object 'obj'";
+ }
+ };
+CODE);
+
+// invoke methods of an object in script world
+// from javax.script.Invocable interface. But, hey,
+// calling code is JavaScript and don't worry about types :)
+
+// get that script object on which to call a method
+var scriptObj = engine.get("obj");
+// call 'func' method on object 'obj'
+engine.invokeMethod(scriptObj, "func");
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/engine/exposevar.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Example showing how to expose a script global var from caller
+
+var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
+// create manager
+var manager = new ScriptEngineManager();
+// create engine
+var engine = manager.getEngineByName("js");
+
+// expose variable to engine
+engine.put("name", "Nashorn");
+
+// access it from script
+engine.eval("print('Hello, ' + name)");
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/engine/foreignobject.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,71 @@
+#// Usage: jjs -scripting foreignobject.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// cross nashorn engine scripting
+// access script objects from other engines in natural syntax
+
+var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
+// create manager
+var manager = new ScriptEngineManager();
+// create engine
+var engine = manager.getEngineByName("js");
+
+// eval code!
+engine.eval(<<CODE
+ var obj = {
+ foo: 42,
+ func: function() {
+ print("func: " + this.foo);
+ }
+ };
+CODE);
+
+// Nashorn engine returns script objects as instance of
+// the class jdk.nashorn.api.scripting.ScriptObjectMirror
+// But nashorn's dynalink linker can treat these objects
+// specially to support natural script syntax to access..
+// In Java code, you need to use ScriptObjectMirror's
+// methods though. Once again, script world is simpler :-)
+
+var foreignObj = engine.get("obj");
+// access properties, functions of it
+// with natural syntax
+print(foreignObj.foo);
+foreignObj.func();
+print(typeof foreignObj.func);
+
+// access engine's global
+var foreignGlobal = engine.eval("this");
+// create objects in engine's world from here!
+print(new foreignGlobal.Object());
+print(new foreignGlobal.Date());
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/engine/hello.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Simple hello world example showing create engine
+// and eval simple script
+
+var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
+// create manager
+var manager = new ScriptEngineManager();
+// create engine
+var engine = manager.getEngineByName("js");
+// eval code!
+engine.eval("print('hello world')");
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/engine/interface.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,60 @@
+#// Usage: jjs -scripting interface.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Example demonstrating how to implement a Java interface
+// whose methods are backed by global script functions
+
+var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
+// create manager
+var manager = new ScriptEngineManager();
+// create engine
+var engine = manager.getEngineByName("js");
+
+// eval code - too many script escapes?
+// use heredoc !
+engine.eval(<<CODE
+function run() {
+ print("run global function called");
+}
+CODE);
+
+// create Java interface object whose methods are
+// implemented by script functions. This is from
+// javax.script.Invocable. But we are in JS world,
+// don't worry about types :)
+
+var Runnable = Java.type("java.lang.Runnable");
+var r = engine.getInterface(Runnable.class);
+print(r.class);
+
+r.run();
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/engine/interface2.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,63 @@
+#// Usage: jjs -scripting interface2.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Simple example demonstrating how to implement java interface
+// whose methods are backed by script methods of a script object
+
+var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
+// create manager
+var manager = new ScriptEngineManager();
+// create engine
+var engine = manager.getEngineByName("js");
+
+// eval code - too many script escapes?
+// use heredoc !
+engine.eval(<<CODE
+ var obj = {
+ run: function() {
+ print("I am run method of 'obj'");
+ }
+ };
+CODE);
+
+// create Java interface object whose methods are
+// implemented by script methods of a script object
+// This is from javax.script.Invocable. But we are
+// in JS world, don't worry about types :)
+
+var Runnable = Java.type("java.lang.Runnable");
+
+var scriptObj = engine.get("obj");
+var r = engine.getInterface(scriptObj, Runnable.class);
+print(r.class);
+r.run();
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/engine/lambda_as_func.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Simple example demonstrating how to expose 'function's
+// from embedding code. Any lambda object exposed to engine
+// can be called as 'function' in script.
+
+var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
+// create manager
+var manager = new ScriptEngineManager();
+// create engine
+var engine = manager.getEngineByName("js");
+
+// Any lambda (@FunctionalInterface annotated type) object can be
+// be exposed from script embedding code. Script can call
+// it as a function
+engine.put("upper", new java.util.function.Function() {
+ apply: function(x) x.toUpperCase()
+});
+
+print(engine.eval("upper('hello')"));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/env.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,43 @@
+#// Usage: jjs -scripting env.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// In nashorn -scripting mode,
+// "$ENV" object exposes process
+// environment variables
+
+print($ENV.PATH);
+print($ENV.JAVA_HOME);
+
+for (i in $ENV) {
+ print(i, "->", $ENV[i]);
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/expression_closure.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// nashorn supports expression closures extension of
+// Mozilla JavaScript 1.8. See also
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8
+
+// leave {, } and 'return' keyword
+
+function sqr(x) x*x;
+
+// prints 289 (= 17*17)
+print(sqr(17));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/fileline.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// nashorn supports pseudo global variables __FILE__
+// and __LINE__ that expands to currently executed
+// script file name and current script line number
+
+// prints current file and line number
+print("executing " + __FILE__ + " @ " + __LINE__);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/fizzbuzz.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// What is FizzBuzz? http://c2.com/cgi/wiki?FizzBuzzTest
+
+// Yet another FizzBuzz impl. using Java 8 lambda and stream
+// but using Nashorn. This is ECMAScript port of @stuartmarks'
+// Java implementation
+
+var IntStream = Java.type("java.util.stream.IntStream");
+
+function ifmod(m, r, f) {
+ return function(i) { return i % m == 0? r : f(i); }
+}
+
+// pass script function for lambda
+IntStream.rangeClosed(1, 100).
+ mapToObj(
+ ifmod(15, "FizzBuzz", ifmod(5, "Buzz", ifmod(3, "Fizz", String))))
+ .forEach(print);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/for_each.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// nashorn supports for..each extension supported
+// by Mozilla. See also
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for_each...in
+
+var strs = [ "hello", "world" ];
+for each (str in strs)
+ print(str);
+
+// create a java int[] object
+var JArray = Java.type("int[]");
+var arr = new JArray(10);
+
+// store squares as values
+for (i in arr)
+ arr[i] = i*i;
+
+// for .. each on java arrays
+print("squares");
+for each (i in arr)
+ print(i);
+
+var System = Java.type("java.lang.System");
+
+// for..each on java Iterables
+// print System properties as name = value pairs
+print("System properties");
+for each (p in System.properties.entrySet()) {
+ print(p.key, "=", p.value);
+}
+
+// print process environment vars as name = value pairs
+print("Process environment");
+for each (e in System.env.entrySet()) {
+ print(e.key, "=", e.value);
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/gaussian_random.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// print 100 Guassian distributed numbers
+
+var Random = Java.type("java.util.Random");
+var DoubleStream = Java.type("java.util.stream.DoubleStream");
+
+var r = new Random();
+
+// expression closure (see expression_closure.js as well)
+// passed as lambda double generator. "print" passed as
+// double consumer lambda to 'forEach' method.
+
+DoubleStream
+ .generate(function() r.nextGaussian())
+ .limit(100)
+ .forEach(print);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/gaussian_random_bind.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// print 100 Guassian distributed numbers
+
+var Random = Java.type("java.util.Random");
+var DoubleStream = Java.type("java.util.stream.DoubleStream");
+
+// function as lambda double generator. "print" passed as
+// double consumer lambda to 'forEach' method.
+// Function.prototype.bind used to attach 'state' for the
+// generator function.
+
+DoubleStream
+ .generate(
+ function(r) {
+ return r.nextGaussian()
+ }.bind(this, new Random()))
+ .limit(100)
+ .forEach(print);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/gutenberg.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,142 @@
+#// Usage: jjs -scripting gutenberg.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Simple example that demonstrates reading XML Rss feed
+// to generate a HTML file from script and show it by browser
+
+// Java classes used
+var Characters = Java.type("javax.xml.stream.events.Characters");
+var Factory = Java.type("javax.xml.stream.XMLInputFactory");
+var File = Java.type("java.io.File");
+var FileWriter = Java.type("java.io.FileWriter");
+var PrintWriter = Java.type("java.io.PrintWriter");
+var URL = Java.type("java.net.URL");
+
+// read Rss feed from a URL. Returns an array
+// of objects having only title and link properties
+function readRssFeed(url) {
+ var fac = Factory.newInstance();
+ var reader = fac.createXMLEventReader(url.openStream());
+
+ // get text content from next event
+ function getChars() {
+ var result = "";
+ var e = reader.nextEvent();
+ if (e instanceof Characters) {
+ result = e.getData();
+ }
+ return result;
+ }
+
+ var items = [];
+ var title, link;
+ var inItem = false;
+ while (reader.hasNext()) {
+ var evt = reader.nextEvent();
+ if (evt.isStartElement()) {
+ var local = evt.name.localPart;
+ if (local == "item") {
+ // capture title, description now
+ inItem = true;
+ }
+
+ if (inItem) {
+ switch (local) {
+ case 'title':
+ title = getChars();
+ break;
+ case 'link':
+ link = getChars();
+ break;
+ }
+ }
+ } else if (evt.isEndElement()) {
+ var local = evt.name.localPart;
+ if (local == "item") {
+ // one item done, save it in result array
+ items.push({ title: title, link: link });
+ inItem = false;
+ }
+ }
+ }
+
+ return items;
+}
+
+// generate simple HTML for an RSS feed
+function getBooksHtml() {
+ var url = new URL("http://www.gutenberg.org/cache/epub/feeds/today.rss");
+ var items = readRssFeed(url);
+
+ var str = "<ul>";
+
+ // Nashorn's string interpolation and heredoc
+ // support is very handy in generating text content
+ // that is filled with elements from runtime objects.
+ // We insert title and link in <li> elements here.
+ for each (i in items) {
+ str += <<EOF
+<li>
+ <a href="${i.link}">${i.title}</a>
+</li>
+EOF
+ }
+ str += "</ul>";
+ return str;
+}
+
+// write the string to the given file
+function writeTo(file, str) {
+ var w = new PrintWriter(new FileWriter(file));
+ try {
+ w.print(str);
+ } finally {
+ w.close();
+ }
+}
+
+// generate books HTML
+var str = getBooksHtml();
+
+// write to file. __DIR__ is directory where
+// this script is stored.
+var file = new File(__DIR__ + "books.html");
+writeTo(file, str);
+
+// show it by desktop browser
+try {
+ var Desktop = Java.type("java.awt.Desktop");
+ Desktop.desktop.browse(file.toURI());
+} catch (e) {
+ print(e);
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/heredoc.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,51 @@
+#// Usage: jjs -scripting heredoc.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Nashorn supports Shell script like here-documents
+// in -scripting mode. Here-docs are multi-line strings
+// that are possibly interpolated with ${} expressions
+// See also http://en.wikipedia.org/wiki/Here_document
+
+var sender = "Buffy the Vampire Slayer";
+var recipient = "Spike";
+
+print(<<END
+
+Dear ${recipient},
+
+I wish you to leave Sunnydale and never return.
+
+Not Quite Love,
+${sender}
+
+END);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/interface_impl.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// nashorn supports Java interface implementation
+// by script using anonymous class-like syntax
+
+var Runnable = Java.type("java.lang.Runnable");
+var Thread = Java.type("java.lang.Thread");
+// use anonymous class-like new syntax
+var r = new Runnable() {
+ run: function() {
+ print("I am a runnable " + Thread.currentThread());
+ }
+}
+
+r.run();
+
+var t = new Thread(r);
+t.start();
+t.join();
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/javaastviewer.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,202 @@
+#// Usage: jjs -fx javaastviewer.js -- <.java files>
+
+/*
+ * Copyright (c) 2014, 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 example demonstrates Java subclassing by Java.extend
+// and javac Compiler and Tree API. This example also uses
+// -fx and javafx TreeView to visualize Java AST as TreeView
+
+if (!$OPTIONS._fx || arguments.length == 0) {
+ print("Usage: jjs -fx javaastviewer.js -- <.java files>");
+ exit(1);
+}
+
+// Java types used
+var Enum = Java.type("java.lang.Enum");
+var HashSet = Java.type("java.util.HashSet");
+var Name = Java.type("javax.lang.model.element.Name");
+var List = Java.type("java.util.List");
+var Set = Java.type("java.util.Set");
+var SimpleTreeVisitor = Java.type("com.sun.source.util.SimpleTreeVisitor");
+var StringArray = Java.type("java.lang.String[]");
+var ToolProvider = Java.type("javax.tools.ToolProvider");
+var Tree = Java.type("com.sun.source.tree.Tree");
+
+function javaASTToScriptObject(args) {
+ // properties ignored (javac implementation class properties) in AST view.
+ // may not be exhaustive - any getAbc would become "abc" property or
+ // public field becomes a property of same name.
+ var ignoredProps = new HashSet();
+ for each (var word in
+ ['extending', 'implementing', 'init', 'mods', 'clazz', 'defs',
+ 'expr', 'tag', 'preferredPosition', 'qualid', 'recvparam',
+ 'restype', 'params', 'startPosition', 'thrown',
+ 'tree', 'typarams', 'typetag', 'vartype']) {
+ ignoredProps.add(word);
+ }
+
+ // get the system compiler tool
+ var compiler = ToolProvider.systemJavaCompiler;
+
+ // get standard file manager
+ var fileMgr = compiler.getStandardFileManager(null, null, null);
+
+ // make a list of compilation unit from command line argument file names
+ // Using Java.to convert script array (arguments) to a Java String[]
+ var compUnits = fileMgr.getJavaFileObjects(Java.to(args, StringArray));
+
+ // create a new compilation task
+ var task = compiler.getTask(null, fileMgr, null, null, null, compUnits);
+
+ // subclass SimpleTreeVisitor - converts Java AST node to
+ // a simple script object by walking through it
+ var ConverterVisitor = Java.extend(SimpleTreeVisitor);
+
+ var visitor = new ConverterVisitor() {
+ // convert java AST node to a friendly script object
+ // which can be viewed. Every node ends up in defaultAction
+ // method of SimpleTreeVisitor method.
+
+ defaultAction: function (node, p) {
+ var resultObj = {};
+ // Nashorn does not iterate properties and methods of Java objects
+ // But, we can bind properties of any object (including java objects)
+ // to a script object and iterate it!
+ var obj = {};
+ Object.bindProperties(obj, node);
+
+ // we don't want every property, method of java object
+ for (var prop in obj) {
+ var val = obj[prop];
+ var type = typeof val;
+ // ignore 'method' members
+ if (type == 'function' || type == 'undefined') {
+ continue;
+ }
+
+ // ignore properties from Javac implementation
+ // classes - hack by name!!
+ if (ignoredProps.contains(prop)) {
+ continue;
+ }
+
+ // subtree - recurse it
+ if (val instanceof Tree) {
+ resultObj[prop] = visitor.visit(val, p);
+ } else if (val instanceof List) {
+ // List of trees - recurse each and make an array
+ var len = val.size();
+ if (len != 0) {
+ var arr = [];
+ for (var j = 0; j < len; j++) {
+ var e = val[j];
+ if (e instanceof Tree) {
+ arr.push(visitor.visit(e, p));
+ }
+ }
+ resultObj[prop] = arr;
+ }
+ } else if (val instanceof Set) {
+ // Set - used for modifier flags
+ // make array
+ var len = val.size();
+ if (len != 0) {
+ var arr = [];
+ for each (var e in val) {
+ if (e instanceof Enum || typeof e == 'string') {
+ arr.push(e.toString());
+ }
+ }
+ resultObj[prop] = arr;
+ }
+ } else if (val instanceof Enum || val instanceof Name) {
+ // make string for any Enum or Name
+ resultObj[prop] = val.toString();
+ } else if (type != 'object') {
+ // primitives 'as is'
+ resultObj[prop] = val;
+ }
+ }
+ return resultObj;
+ }
+ }
+
+ // top level object with one property for each compilation unit
+ var scriptObj = {};
+ for each (var cu in task.parse()) {
+ scriptObj[cu.sourceFile.name] = cu.accept(visitor, null);
+ }
+
+ return scriptObj;
+}
+
+// JavaFX classes used
+var StackPane = Java.type("javafx.scene.layout.StackPane");
+var Scene = Java.type("javafx.scene.Scene");
+var TreeItem = Java.type("javafx.scene.control.TreeItem");
+var TreeView = Java.type("javafx.scene.control.TreeView");
+
+// Create a javafx TreeItem to view a script object
+function treeItemForObject(obj, name) {
+ var item = new TreeItem(name);
+ for (var prop in obj) {
+ var node = obj[prop];
+ if (typeof node == 'object') {
+ if (node == null) {
+ // skip nulls
+ continue;
+ }
+ var subitem = treeItemForObject(node, prop);
+ } else {
+ var subitem = new TreeItem(prop + ": " + node);
+ }
+ item.children.add(subitem);
+ }
+
+ item.expanded = true;
+ return item;
+}
+
+var commandArgs = arguments;
+
+// JavaFX start method
+function start(stage) {
+ var obj = javaASTToScriptObject(commandArgs);
+ stage.title = "Java AST Viewer"
+ var rootItem = treeItemForObject(obj, "AST");
+ rootItem.expanded = true;
+ var tree = new TreeView(rootItem);
+ var root = new StackPane();
+ root.children.add(tree);
+ stage.scene = new Scene(root, 300, 450);
+ stage.show();
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/javacastcounter.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Usage: jjs javacastcounter.js -- <.java files>
+
+// This example demonstrates Nashorn Java.extend API
+// to subclass a Java class from script.
+
+// This example uses Javac Compiler and Tree API
+// to list type casts used in java source files.
+
+if (arguments.length == 0) {
+ print("Usage: jjs javacastcounter.js -- <.java files>");
+ exit(1);
+}
+
+// Java types used
+var ToolProvider = Java.type("javax.tools.ToolProvider");
+var TreeScanner = Java.type("com.sun.source.util.TreeScanner");
+var Trees = Java.type("com.sun.source.util.Trees");
+var StringArray = Java.type("java.lang.String[]");
+
+// get the system compiler tool
+var compiler = ToolProvider.systemJavaCompiler;
+
+// get standard file manager
+var fileMgr = compiler.getStandardFileManager(null, null, null);
+
+// make a list of compilation unit from command line argument file names
+// Using Java.to convert script array (arguments) to a Java String[]
+var compUnits = fileMgr.getJavaFileObjects(Java.to(arguments, StringArray));
+
+// create a new compilation task
+var task = compiler.getTask(null, fileMgr, null, null, null, compUnits);
+
+// SourcePositions object to get positions of AST nodes
+var sourcePositions = Trees.instance(task).sourcePositions;
+
+// Subclass TreeScanner class
+var CastCounter = Java.extend(TreeScanner);
+
+var counter = new CastCounter() {
+ // current CompilationUnitTree
+ compUnit: null,
+ // current LineMap (pos -> line, column)
+ lineMap: null,
+ // current compilation unit's file name
+ fileName: null,
+
+ // overrides of TreeScanner methods
+
+ visitCompilationUnit: function(node, p) {
+ // capture info about current Compilation unit
+ this.compUnit = node;
+ this.lineMap = node.lineMap;
+ this.fileName = node.sourceFile.name;
+
+ // Using Java.super API to call super class method here
+ return Java.super(counter).visitCompilationUnit(node, p);
+ },
+
+ visitTypeCast: function(node, p) {
+ // print information on this type cast node
+ var pos = sourcePositions.getStartPosition(this.compUnit, node);
+ var line = this.lineMap.getLineNumber(pos);
+ var col = this.lineMap.getColumnNumber(pos);
+ print(node + " @ " + this.fileName + ":" + line + ":" + col);
+
+ // count one more type cast
+ return 1;
+ },
+
+ reduce: function(r1, r2) {
+ return (r1 == null ? 0 : r1) + (r2 == null ? 0 : r2);
+ }
+};
+
+// print total number of type cast nodes seen
+print("Total casts:", counter.scan(task.parse(), null));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/javaimporter.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// JavaImporter along with 'with' statement helps in
+// localized Java class references
+
+function readTextFromURL(url) {
+
+ // equivalent to
+ //
+ // import java.io.*;
+ // import java.net.*;
+ // import java.lang.StringBuffer;
+ //
+ // only inside the 'with' statement
+ with (new JavaImporter(java.io,
+ java.net,
+ java.lang.StringBuilder)) {
+ var buf = new StringBuilder();
+ var u = new URL(url);
+ var reader = new BufferedReader(
+ new InputStreamReader(u.openStream()));
+ var line = null;
+ try {
+ while ((line = reader.readLine()) != null)
+ buf.append(line).append('\n');
+ } finally {
+ reader.close();
+ }
+
+ return buf.toString();
+ }
+}
+
+print(readTextFromURL("https://twitter.com/"));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/javalist.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Java List elements accessed/modified via
+// array element access/update syntax
+
+var ArrayList = Java.type("java.util.ArrayList");
+var list = new ArrayList();
+
+// add elements to list by List's add method calls
+list.add("js");
+list.add("ecmascript");
+list.add("nashorn");
+
+// get by List's get(int) method
+print(list[0]);
+print(list[1]);
+print(list[2]);
+
+// access list elements by indexed access as well
+print(list[0]);
+print(list[1]);
+print(list[2]);
+
+// assign to list elements by index as well
+list[0] = list[0].toUpperCase();
+list[1] = list[1].toUpperCase();
+list[2] = list[2].toUpperCase();
+
+print(list.get(0));
+print(list.get(1));
+print(list.get(2));
+print(list[0]);
+print(list[1]);
+print(list[2]);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/javamap.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Java Map keys as properties
+
+// Demonstrating Java Map key/value can be accessed
+// as property/value from script.
+
+var HashMap = Java.type("java.util.HashMap");
+var map = new HashMap();
+
+// map key-value access by java get/put method calls
+map.put('js', 'nashorn');
+print(map.get('js'));
+
+// access keys of map as properties
+print(map['js']);
+print(map.js);
+
+// also assign new key-value pair
+// as 'property-value'
+map['language'] = 'java';
+print(map.get("language"));
+print(map.language);
+print(map['language']);
+
+map.answer = 42;
+print(map.get("answer"));
+print(map.answer);
+print(map['answer']);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/javashell.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,146 @@
+#// Usage: jjs -scripting javashell.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Simple Java "shell" with which you can try out
+// your few liner Java code leaving imports, main etc.
+// And you can leave even compilation as this script
+// takes care boilerplate+compile step for you.
+
+// Java types used
+var Arrays = Java.type("java.util.Arrays");
+var BufferedReader = Java.type("java.io.BufferedReader");
+var FileWriter = Java.type("java.io.FileWriter");
+var LocalDateTime = Java.type("java.time.LocalDateTime");
+var InputStreamReader = Java.type("java.io.InputStreamReader");
+var PrintWriter = Java.type("java.io.PrintWriter");
+var ProcessBuilder = Java.type("java.lang.ProcessBuilder");
+var System = Java.type("java.lang.System");
+
+// read multiple lines of input from stdin till user
+// enters an empty line
+function input(endMarker, prompt) {
+ if (!endMarker) {
+ endMarker = "";
+ }
+
+ if (!prompt) {
+ prompt = " >> ";
+ }
+
+ var str = "";
+ var reader = new BufferedReader(new InputStreamReader(System.in));
+ var line;
+ while (true) {
+ System.out.print(prompt);
+ line = reader.readLine();
+ if (line == null || line == endMarker) {
+ break;
+ }
+ str += line + "\n";
+ }
+ return str;
+}
+
+// write the string to the given file
+function writeTo(file, str) {
+ var w = new PrintWriter(new FileWriter(file));
+ try {
+ w.print(str);
+ } finally {
+ w.close();
+ }
+}
+
+// generate Java code with user's input
+// put inside generated main method
+function generate(className) {
+ var usercode = input();
+ if (usercode == "") {
+ return false;
+ }
+
+ var fullcode = <<EOF
+// userful imports, add more here if you want
+// more imports.
+import static java.lang.System.*;
+import java.io.*;
+import java.net.*;
+import java.math.*;
+import java.nio.file.*;
+import java.time.*;
+import java.time.chrono.*;
+import java.time.format.*;
+import java.time.temporal.*;
+import java.time.zone.*;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.function.*;
+import java.util.stream.*;
+
+public class ${className} {
+ public static void main(String[] args) throws Exception {
+ ${usercode}
+ }
+}
+EOF
+
+ writeTo("${className}.java", fullcode);
+ return true;
+}
+
+// execute code command
+function exec(args) {
+ // build child process and start it!
+ new ProcessBuilder(Arrays.asList(args.split(' ')))
+ .inheritIO()
+ .start()
+ .waitFor();
+}
+
+// generate unique name
+function uniqueName() {
+ var now = LocalDateTime.now().toString();
+ // replace unsafe chars with '_'
+ return "JavaShell" + now.replace(/-|:|\./g, '_');
+}
+
+// read-compile-run loop
+while(true) {
+ var className = uniqueName();
+ if (generate(className)) {
+ exec("javac ${className}.java");
+ exec("java ${className}");
+ } else {
+ break;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/jsadapter_dom.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,189 @@
+#// Usage: jjs -scripting jsadapter_dom.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Simple example that demonstrates reading XML Rss feed
+// to generate a HTML file from script and show it by browser
+// Uses XML DOM parser and DOM element wrapped by script
+// "proxy" (JSAdapter constructor)
+
+// Java classes used
+var DocBuilderFac = Java.type("javax.xml.parsers.DocumentBuilderFactory");
+var Node = Java.type("org.w3c.dom.Node");
+var File = Java.type("java.io.File");
+var FileWriter = Java.type("java.io.FileWriter");
+var PrintWriter = Java.type("java.io.PrintWriter");
+
+// constants from Node class
+var ELEMENT_NODE = Node.ELEMENT_NODE;
+var TEXT_NODE = Node.TEXT_NODE;
+
+// parse XML from uri and return Document
+function parseXML(uri) {
+ var docBuilder = DocBuilderFac.newInstance().newDocumentBuilder();
+ return docBuilder["parse(java.lang.String)"](uri);
+}
+
+// get child Elements of given name of the parent element given
+function getChildElements(elem, name) {
+ var nodeList = elem.childNodes;
+ var childElems = [];
+ var len = nodeList.length;
+ for (var i = 0; i < len; i++) {
+ var node = nodeList.item(i);
+ if (node.nodeType == ELEMENT_NODE &&
+ node.tagName == name) {
+ childElems.push(wrapElement(node));
+ }
+ }
+
+ return childElems;
+}
+
+// get concatenated child text content of an Element
+function getElemText(elem) {
+ var nodeList = elem.childNodes;
+ var len = nodeList.length;
+ var text = '';
+ for (var i = 0; i < len; i++) {
+ var node = nodeList.item(i);
+ if (node.nodeType == TEXT_NODE) {
+ text += node.nodeValue;
+ }
+ }
+
+ return text;
+}
+
+// Wrap DOM Element object as a convenient script object
+// using JSAdapter. JSAdapter is like java.lang.reflect.Proxy
+// in that it allows property access, method calls be trapped
+// by 'magic' methods like __get__, __call__.
+function wrapElement(elem) {
+ if (! elem) {
+ return elem;
+ }
+ return new JSAdapter() {
+ // getter to expose child elements and attributes by name
+ __get__: function(name) {
+ if (typeof name == 'string') {
+ if (name.startsWith('@')) {
+ var attr = elem.getAttributeNode(name.substring(1));
+ return !attr? undefined : attr.value;
+ }
+
+ var arr = getChildElements(elem, name);
+ if (arr.length == 1) {
+ // single child element, expose as single element
+ return arr[0];
+ } else {
+ // multiple children of given name, expose as array
+ return arr;
+ }
+ }
+ return undefined;
+ },
+
+ __call__: function(name) {
+ // toString override to get text content of this Element
+ if (name == 'toString' || name == 'valueOf') {
+ return getElemText(elem);
+ }
+ return undefined;
+ }
+ }
+}
+
+// generate HTML using here-doc and string interpolation
+function getBooksHtml() {
+ var doc = parseXML("http://www.gutenberg.org/cache/epub/feeds/today.rss");
+ // wrap document root Element as script convenient object
+ var rss = wrapElement(doc.documentElement);
+ print("rss file version " + rss['@version']);
+
+ var str = <<HEAD
+
+<html>
+<title>${rss.channel.title}</title>
+<body>
+<h1>${rss.channel.description}</h1>
+<p>
+Published on ${rss.channel.pubDate}
+</p>
+
+HEAD
+
+ var items = rss.channel.item;
+ for each (var i in items) {
+ str += <<LIST
+
+<dl>
+<dt><a href="${i.link}">${i.title}</a></dt>
+<dd>${i.description}</dd>
+</dl>
+
+LIST
+ }
+ str += <<END
+
+</body>
+</html>
+
+END
+ return str;
+}
+
+// write the string to the given file
+function writeTo(file, str) {
+ var w = new PrintWriter(new FileWriter(file));
+ try {
+ w.print(str);
+ } finally {
+ w.close();
+ }
+}
+
+// generate books HTML
+var str = getBooksHtml();
+
+// write to file. __DIR__ is directory where
+// this script is stored.
+var file = new File(__DIR__ + "books.html");
+writeTo(file, str);
+
+// show it by desktop browser
+try {
+ var Desktop = Java.type("java.awt.Desktop");
+ Desktop.desktop.browse(file.toURI());
+} catch (e) {
+ print(e);
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/jsobject.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,75 @@
+#// Usage: jjs -scripting -cp . jsobject.js
+
+/*
+ * Copyright (c) 2014, 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 sample demonstrats how to expose a
+// script friendly object from your java code
+// by implementing jdk.nashorn.api.scripting.JSObject
+
+// compile the java program
+`javac BufferArray.java`;
+
+// print error, if any and exit
+if ($ERR != '') {
+ print($ERR);
+ exit($EXIT);
+}
+
+// create BufferArray
+var BufferArray = Java.type("BufferArray");
+var bb = new BufferArray(10);
+
+// 'magic' methods called to retrieve set/get
+// properties on BufferArray instance
+var len = bb.length;
+print("bb.length = " + len)
+for (var i = 0; i < len; i++) {
+ bb[i] = i*i;
+}
+
+for (var i = 0; i < len; i++) {
+ print(bb[i]);
+}
+
+// get underlying buffer by calling a method
+// on BufferArray magic object
+
+// 'buf' is a function member
+print(typeof bb.buf);
+var buf = bb.buf();
+
+// use retrieved underlying nio buffer
+var cap = buf.capacity();
+print("buf.capacity() = " + cap);
+for (var i = 0; i < cap; i++) {
+ print(buf.get(i));
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/jsobject_mapreduce.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,62 @@
+#// Usage: jjs -scripting -cp . jsobject_mapreduce.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Many Array.prototype functions such as map,
+// filter, reduce, reduceRight, every, some are generic.
+// These functions accept ECMAScript array as well as
+// many array-like objects including JSObjects.
+// See also http://en.wikipedia.org/wiki/MapReduce
+
+`javac BufferArray.java`;
+
+var BufferArray = Java.type("BufferArray");
+var buf = new BufferArray(10);
+
+var map = Array.prototype.map;
+var filter = Array.prototype.filter;
+var reduce = Array.prototype.reduce;
+
+// make random list of numbers
+for (var i = 0; i < 10; i++)
+ buf[i] = Math.random();
+
+var forEach = Array.prototype.forEach;
+// print numbers in the list
+forEach.call(buf, function(x) print(x));
+
+// print sum of squares of the random numbers
+print("Square sum:",
+ reduce.call(
+ map.call(buf, function(x) x*x),
+ function(x, y) x + y)
+);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/jsonviewer.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,120 @@
+#// Usage: jjs -fx jsonviewer.js
+// or
+// jjs -fx jsonviewer.js -- <url-of-json-doc>
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+if (! $OPTIONS._fx) {
+ print("Usage: jjs -fx jsonviewer.js -- <url-of-json-doc>");
+ exit(1);
+}
+
+// This example downloads a JSON file from a URL and
+// shows the same as a JavaFX tree view.
+
+// Using JavaFX from Nashorn. See also:
+// http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/javafx.html
+
+// JavaFX classes used
+var StackPane = Java.type("javafx.scene.layout.StackPane");
+var Scene = Java.type("javafx.scene.Scene");
+var TreeItem = Java.type("javafx.scene.control.TreeItem");
+var TreeView = Java.type("javafx.scene.control.TreeView");
+
+// read text content of a URL
+function readTextFromURL(url) {
+ // equivalent to
+ //
+ // import java.io.*;
+ // import java.net.*;
+ // import java.lang.StringBuffer;
+ //
+ // only inside the 'with' statement
+ with (new JavaImporter(java.io,
+ java.net,
+ java.lang.StringBuilder)) {
+ var buf = new StringBuilder();
+ var u = new URL(url);
+ var reader = new BufferedReader(
+ new InputStreamReader(u.openStream()));
+ var line = null;
+ try {
+ while ((line = reader.readLine()) != null)
+ buf.append(line).append('\n');
+ } finally {
+ reader.close();
+ }
+
+ return buf.toString();
+ }
+}
+
+// Create a javafx TreeItem to view a script object
+function treeItemForObject(obj, name) {
+ var item = new TreeItem(name);
+ for (var prop in obj) {
+ var node = obj[prop];
+ if (typeof node == 'object') {
+ if (node == null) {
+ // skip nulls
+ continue;
+ }
+
+ if (Array.isArray(node) && node.length == 0) {
+ // skip empty arrays
+ continue;
+ }
+
+ var subitem = treeItemForObject(node, prop);
+ } else {
+ var subitem = new TreeItem(prop + ": " + node);
+ }
+ item.children.add(subitem);
+ }
+ return item;
+}
+
+var DEFAULT_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?q=Chennai&mode=json&units=metric&cnt=7`";
+
+var url = arguments.length == 0? DEFAULT_URL : arguments[0];
+var obj = JSON.parse(readTextFromURL(url));
+
+// JavaFX start method
+function start(stage) {
+ stage.title = "JSON Viewer";
+ var rootItem = treeItemForObject(obj, url);
+ var tree = new TreeView(rootItem);
+ var root = new StackPane();
+ root.children.add(tree);
+ stage.scene = new Scene(root, 300, 450);
+ stage.show();
+}
--- a/nashorn/samples/letter.js Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/samples/letter.js Mon May 12 09:37:50 2014 -0700
@@ -1,3 +1,5 @@
+#// Usage: jjs -scripting letter.js -- <sender> <recipient>
+
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
*
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/list_mapreduce.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Usage: jjs list_mapreduce.js
+
+// Many Array.prototype functions such as map,
+// filter, reduce, reduceRight, every, some are generic.
+// These functions accept ECMAScript array as well as
+// many array-like objects including java.util.ArrayLists.
+// So, you can do map/filter/reduce with Java streams or
+// you can also use Array.prototype functions as below.
+// See also http://en.wikipedia.org/wiki/MapReduce
+
+var ArrayList = Java.type("java.util.ArrayList");
+var list = new ArrayList();
+list.add("nashorn");
+list.add("ecmascript");
+list.add("javascript");
+list.add("js");
+list.add("scheme");
+
+var map = Array.prototype.map;
+var filter = Array.prototype.filter;
+var reduce = Array.prototype.reduce;
+
+// sum of word lengths
+print("Sum word length:",
+ reduce.call(
+ map.call(list, function(x) x.length),
+ function(x, y) x + y)
+);
+
+// filter use to filter out "j*" and concatenate rest with ":"
+// after uppercasing all strings
+print(
+ reduce.call(
+ map.call(
+ filter.call(list, function(x) !x.startsWith("j")),
+ function(x) x.toUpperCase()),
+ function(x, y) x + ":" + y)
+);
+
+// another list example involving numbers
+list.clear();
+// make random list of numbers
+for (var i = 0; i < 10; i++)
+ list.add(Math.random());
+
+var forEach = Array.prototype.forEach;
+// print numbers in the list
+forEach.call(list, function(x) print(x));
+
+// print sum of squares of the random numbers
+print("Square sum:",
+ reduce.call(
+ map.call(list, function(x) x*x),
+ function(x, y) x + y)
+);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/locales.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Simple program that lists available locals. This is ECMAScript
+// port of Java example by @brunoborges
+
+// Java classes used
+var Arrays = Java.type("java.util.Arrays");
+var Collectors = Java.type("java.util.stream.Collectors");
+var JString = Java.type("java.lang.String");
+var Locale = Java.type("java.util.Locale");
+
+var formatStr = "Country : %s \t\t\t\t:\t Country Code : %s";
+
+// Nashorn allows script functions to be passed
+// whereever Java8 lambdas are expected.
+
+// Nashorn also supports "expression closures" supported by
+// Mozilla JavaScript 1.8 version. See also
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8
+
+// The following prints locales in (country) display name order
+var list = Arrays.asList(Locale.getISOCountries())
+ .stream()
+ .map(function(x) new Locale("", x))
+ .sorted(function(c0, c1) c0.displayCountry.compareTo(c1.displayCountry))
+ .map(function(l) JString.format(formatStr, l.displayCountry, l.country))
+ .collect(Collectors.toList());
+
+list.forEach(print);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/logisticmap.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,82 @@
+#// Usage: jjs -fx -scripting logisticmap.js -- <initial_x> <R>
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Logistic map viewer using Java8 Streams and JavaFX
+// See also http://en.wikipedia.org/wiki/Logistic_map
+
+if (!$OPTIONS._fx || arguments.length < 2) {
+ print("Usage: jjs -fx -scripting logisticmap.js -- <initial_x> <R>");
+ exit(1);
+}
+
+// parameters for the logistic map
+var x = parseFloat(arguments[0]);
+var R = parseFloat(arguments[1]);
+var NUM_POINTS = arguments.length > 2? parseFloat(arguments[2]) : 20;
+
+// Java classes used
+var DoubleStream = Java.type('java.util.stream.DoubleStream');
+var LineChart = Java.type("javafx.scene.chart.LineChart");
+var NumberAxis = Java.type("javafx.scene.chart.NumberAxis");
+var Scene = Java.type("javafx.scene.Scene");
+var Stage = Java.type("javafx.stage.Stage");
+var XYChart = Java.type("javafx.scene.chart.XYChart");
+
+function start(stage) {
+ stage.title = "Logistic Map: initial x = ${x}, R = ${R}";
+ // make chart
+ var xAxis = new NumberAxis();
+ var yAxis = new NumberAxis();
+ var lineChart = new LineChart(xAxis, yAxis);
+ xAxis.setLabel("iteration");
+ yAxis.setLabel("x");
+ // make chart data series
+ var series = new XYChart.Series();
+ var data = series.data;
+ // populate data using logistic iteration
+ var i = 0;
+ DoubleStream
+ .generate(function() x = R*x*(1-x))
+ .limit(NUM_POINTS)
+ .forEach(
+ function(value) {
+ data.add(new XYChart.Data(i, value));
+ i++;
+ }
+ );
+ // add to stage
+ var scene = new Scene(lineChart, 800, 600);
+ lineChart.data.add(series);
+ stage.scene = scene;
+ stage.show();
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/options.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,37 @@
+#// Usage: jjs -scripting options.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// print all option names and values
+for (i in $OPTIONS) {
+ print(i, '=', $OPTIONS[i]);
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/readLine.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,38 @@
+#// Usage: jjs -scripting greeting.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// readLine prints prompt and reads user response
+var name = readLine("Your name please: ");
+
+// user name is interpolated within string
+print("Hello ${name}");
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/sam_function.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// nashorn supports passing script functions whenever
+// a SAM (single abstract method) type object is expected
+
+var System = Java.type("java.lang.System");
+var Timer = Java.type("java.util.Timer");
+var timer = new Timer();
+
+// schedule method accepts java.util.TimerTask
+// which is a single-abstract-method type. you
+// can pass a script function and nashorn will
+// wrap it as SAM implementor.
+
+timer.schedule(function() {
+ print("Hello World!");
+}, 1000);
+
+// wait for timer thread to print by
+// reading from stdin.
+print("press any key to exit after message from timer...");
+System.in.read();
--- a/nashorn/samples/shell.js Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/samples/shell.js Mon May 12 09:37:50 2014 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 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
@@ -29,50 +29,53 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/**
- * This is a simple shell tool in JavaScript.
+// Usage: jjs shell.js
+
+/* This is a simple shell tool in JavaScript.
*
* Runs any operating system command using Java "exec". When "eval" command is
* used, evaluates argument(s) as JavaScript code.
*/
-var imports = new JavaImporter(java.io, java.lang, java.util);
-
-function prompt() {
- java.lang.System.out.print(">");
-}
+(function() {
+ // Java classes used
+ var Arrays = Java.type("java.util.Arrays");
+ var BufferedReader = Java.type("java.io.BufferedReader");
+ var InputStreamReader = Java.type("java.io.InputStreamReader");
+ var ProcessBuilder = Java.type("java.lang.ProcessBuilder");
+ var System = Java.type("java.lang.System");
-with (imports) {
- var reader = new BufferedReader(new InputStreamReader(System["in"]));
- var line = null;
+ // print prompt
+ function prompt() {
+ System.out.print("> ");
+ }
+
+ var reader = new BufferedReader(new InputStreamReader(System.in));
prompt();
- while ((line = reader.readLine()) != null) {
- if (line != "") {
- var args = line.split(" ");
+ // read and evaluate each line from stdin
+ reader.lines().forEach(function(line) {
+ if (! line.isEmpty()) {
+ var args = line.split(' ');
try {
- if (args[0] == "eval") {
- var code = line.substring("eval".length);
+ // special 'eval' command to evaluate JS code
+ if (args[0] == 'eval') {
+ var code = line.substring('eval'.length);
var res = eval(code);
if (res != undefined) {
print(res);
}
} else {
- var argList = new ArrayList();
- for (i in args) { argList.add(args[i]); }
- var procBuilder = new ProcessBuilder(argList);
- procBuilder.redirectErrorStream();
- var proc = procBuilder.start();
- var out = new BufferedReader(new InputStreamReader(proc.getInputStream()));
- var line = null;
- while ((line = out.readLine()) != null) {
- System.out.println(line);
- }
- proc.waitFor();
+ // build child process and start it!
+ new ProcessBuilder(Arrays.asList(args))
+ .inheritIO()
+ .start()
+ .waitFor();
}
} catch (e) {
+ // print exception, if any
print(e);
}
}
prompt();
- }
-}
+ })
+})()
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/stack.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// nashorn supports 'stack' property on ECMAScript
+// error objects. This property's value is a string
+// that shows script stack trace.
+
+function g() {
+ throw new Error("wrong");
+}
+
+function f() {
+ g();
+}
+
+// Output looks something like:
+//
+// Error: wrong
+// at g (stack.js:37)
+// at f (stack.js:41)
+// at <program> (stack.js:52)
+
+try {
+ f();
+} catch (e) {
+ print(e.stack);
+}
--- a/nashorn/samples/test.js Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/samples/test.js Mon May 12 09:37:50 2014 -0700
@@ -30,4 +30,3 @@
*/
print("Hello World");
-
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/uniform_random.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// generate/print 100 uniformly distributed random values
+// and print summary statistics on it
+
+var DoubleStream = Java.type("java.util.stream.DoubleStream");
+
+// pass script function when a lambda is required
+// Math.random passed here for double generator lambda
+// print passed to forEach method
+
+DoubleStream
+ .generate(Math.random)
+ .limit(100)
+ .forEach(print);
+
+print(DoubleStream
+ .generate(Math.random)
+ .limit(100)
+ .summaryStatistics());
--- a/nashorn/samples/uniq.js Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/samples/uniq.js Mon May 12 09:37:50 2014 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 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
@@ -29,27 +29,28 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/**
- * Prints unique lines from a given file.
- */
+// Usage: jjs uniq.js
+// or: jjs uniq.js -- <file>
+
+// omit repeated lines and print unique lines
-if (arguments.length != 1) {
- print("Usage: jjs uniq.js -- <file>");
- java.lang.System.exit(1);
-}
+var BufferedReader = Java.type("java.io.BufferedReader");
+var FileReader = Java.type("java.io.FileReader");
+var InputStreamReader = Java.type("java.io.InputStreamReader");
+var System = Java.type("java.lang.System");
-var imports = new JavaImporter(java.io);
-
+// use object as set - but insertion order preserved
var uniqueLines = {};
-with (imports) {
- var reader = new BufferedReader(new FileReader(arguments[0]));
- while ((line = reader.readLine()) != null) {
- // using a JS object as a map...
- uniqueLines[line] = true;
- }
+var reader = arguments.length > 0 ?
+ new FileReader(arguments[0]) :
+ new InputStreamReader(System.in);
+reader = new BufferedReader(reader);
+
+// add unique lines
+reader.lines().forEach(function(line) {
+ uniqueLines[line] = true;
+})
+
+for (line in uniqueLines) {
+ print(line);
}
-
-// now print the collected lines
-for (i in uniqueLines) {
- print(i);
-}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/uniqs.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Usage: jjs uniqs.js -- <file>
+// omit repeated lines and print unique lines
+// But this version uses Stream API
+
+if (arguments.length < 1) {
+ print("Usage: jjs uniqs.js -- <file>");
+ exit(1);
+}
+
+var Files = Java.type("java.nio.file.Files");
+var FileSystems = Java.type("java.nio.file.FileSystems");
+print('Unique lines:',
+ Files
+ .lines(FileSystems.default.getPath(arguments[0]))
+ .distinct()
+ .peek(print)
+ .count());
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/weather.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,63 @@
+#// usage: jjs -scripting weather.js
+
+/*
+ * Copyright (c) 2014, 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.
+ */
+
+// Simple nashorn example showing back-quote exec process,
+// JSON and Java8 streams
+
+var Arrays = Java.type("java.util.Arrays");
+
+// use curl to download JSON weather data from the net
+// use backquote -scripting mode syntax to exec a process
+
+`curl http://api.openweathermap.org/data/2.5/forecast/daily?q=Chennai&mode=json&units=metric&cnt=7`;
+
+// parse JSON
+var weather = JSON.parse($OUT);
+
+// pull out humidity as array
+var humidity = weather.list.map(function(curVal) {
+ return curVal.humidity;
+})
+
+// Stream API to print stat
+print("Humidity");
+print(Arrays["stream(int[])"](humidity).summaryStatistics());
+
+// pull maximum day time temperature
+var temp = weather.list.map(function(curVal) {
+ return curVal.temp.max;
+});
+
+// Stream API to print stat
+print("Max Temperature");
+print(Arrays["stream(double[])"](temp).summaryStatistics());
--- a/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java Mon May 12 09:37:50 2014 -0700
@@ -525,6 +525,31 @@
return evalImpl(script, ctxt, getNashornGlobalFrom(ctxt));
}
+ private Object evalImpl(final Context.MultiGlobalCompiledScript mgcs, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
+ final Global oldGlobal = Context.getGlobal();
+ final boolean globalChanged = (oldGlobal != ctxtGlobal);
+ try {
+ if (globalChanged) {
+ Context.setGlobal(ctxtGlobal);
+ }
+
+ final ScriptFunction script = mgcs.getFunction(ctxtGlobal);
+
+ // set ScriptContext variables if ctxt is non-null
+ if (ctxt != null) {
+ setContextVariables(ctxtGlobal, ctxt);
+ }
+ return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
+ } catch (final Exception e) {
+ throwAsScriptException(e, ctxtGlobal);
+ throw new AssertionError("should not reach here");
+ } finally {
+ if (globalChanged) {
+ Context.setGlobal(oldGlobal);
+ }
+ }
+ }
+
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
if (script == null) {
return null;
@@ -571,18 +596,38 @@
}
private CompiledScript asCompiledScript(final Source source) throws ScriptException {
- final ScriptFunction func = compileImpl(source, context);
+ final Context.MultiGlobalCompiledScript mgcs;
+ final ScriptFunction func;
+ final Global oldGlobal = Context.getGlobal();
+ final Global newGlobal = getNashornGlobalFrom(context);
+ final boolean globalChanged = (oldGlobal != newGlobal);
+ try {
+ if (globalChanged) {
+ Context.setGlobal(newGlobal);
+ }
+
+ mgcs = nashornContext.compileScript(source);
+ func = mgcs.getFunction(newGlobal);
+ } catch (final Exception e) {
+ throwAsScriptException(e, newGlobal);
+ throw new AssertionError("should not reach here");
+ } finally {
+ if (globalChanged) {
+ Context.setGlobal(oldGlobal);
+ }
+ }
+
return new CompiledScript() {
@Override
public Object eval(final ScriptContext ctxt) throws ScriptException {
final Global globalObject = getNashornGlobalFrom(ctxt);
- // Are we running the script in the correct global?
+ // Are we running the script in the same global in which it was compiled?
if (func.getScope() == globalObject) {
return evalImpl(func, ctxt, globalObject);
}
- // ScriptContext with a different global. Compile again!
- // Note that we may still hit per-global compilation cache.
- return evalImpl(compileImpl(source, ctxt), ctxt, globalObject);
+
+ // different global
+ return evalImpl(mgcs, ctxt, globalObject);
}
@Override
public ScriptEngine getEngine() {
--- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java Mon May 12 09:37:50 2014 -0700
@@ -1451,7 +1451,10 @@
if (value == null) {
hasGettersSetters = true;
- } else if (key.equals(ScriptObject.PROTO_PROPERTY_NAME)) {
+ } else if (propertyNode.getKey() instanceof IdentNode &&
+ key.equals(ScriptObject.PROTO_PROPERTY_NAME)) {
+ // ES6 draft compliant __proto__ inside object literal
+ // Identifier key and name is __proto__
protoNode = value;
continue;
}
--- a/nashorn/src/jdk/nashorn/internal/objects/Global.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/Global.java Mon May 12 09:37:50 2014 -0700
@@ -1906,6 +1906,13 @@
// Object.getPrototypeOf(Function.prototype) === Object.prototype
anon.setInitialProto(ObjectPrototype);
+ // ES6 draft compliant __proto__ property of Object.prototype
+ // accessors on Object.prototype for "__proto__"
+ final ScriptFunction getProto = ScriptFunctionImpl.makeFunction("getProto", ScriptObject.GETPROTO);
+ final ScriptFunction setProto = ScriptFunctionImpl.makeFunction("setProto", ScriptObject.SETPROTOCHECK);
+ ObjectPrototype.addOwnProperty("__proto__", Attribute.NOT_ENUMERABLE, getProto, setProto);
+
+
// Function valued properties of Function.prototype were not properly
// initialized. Because, these were created before global.function and
// global.object were not initialized.
--- a/nashorn/src/jdk/nashorn/internal/parser/Parser.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/parser/Parser.java Mon May 12 09:37:50 2014 -0700
@@ -33,6 +33,7 @@
import static jdk.nashorn.internal.parser.TokenType.CATCH;
import static jdk.nashorn.internal.parser.TokenType.COLON;
import static jdk.nashorn.internal.parser.TokenType.COMMARIGHT;
+import static jdk.nashorn.internal.parser.TokenType.CONST;
import static jdk.nashorn.internal.parser.TokenType.DECPOSTFIX;
import static jdk.nashorn.internal.parser.TokenType.DECPREFIX;
import static jdk.nashorn.internal.parser.TokenType.ELSE;
@@ -849,6 +850,11 @@
expect(SEMICOLON);
break;
default:
+ if (env._const_as_var && type == CONST) {
+ variableStatement(true);
+ break;
+ }
+
if (type == IDENT || isNonStrictModeIdent()) {
if (T(k + 1) == COLON) {
labelStatement();
@@ -1110,6 +1116,12 @@
case SEMICOLON:
break;
default:
+ if (env._const_as_var && type == CONST) {
+ // Var statements captured in for outer block.
+ vars = variableStatement(false);
+ break;
+ }
+
final Expression expression = expression(unaryExpression(), COMMARIGHT.getPrecedence(), true);
forNode = forNode.setInit(lc, expression);
break;
--- a/nashorn/src/jdk/nashorn/internal/parser/TokenType.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/parser/TokenType.java Mon May 12 09:37:50 2014 -0700
@@ -111,7 +111,7 @@
CATCH (KEYWORD, "catch"),
// CHAR (FUTURE, "char"),
CLASS (FUTURE, "class"),
- CONST (FUTURE, "const"),
+ CONST (KEYWORD, "const"),
CONTINUE (KEYWORD, "continue"),
DEBUGGER (KEYWORD, "debugger"),
DEFAULT (KEYWORD, "default"),
--- a/nashorn/src/jdk/nashorn/internal/runtime/Context.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/Context.java Mon May 12 09:37:50 2014 -0700
@@ -490,6 +490,39 @@
}
/**
+ * Interface to represent compiled code that can be re-used across many
+ * global scope instances
+ */
+ public static interface MultiGlobalCompiledScript {
+ /**
+ * Obtain script function object for a specific global scope object.
+ *
+ * @param newGlobal global scope for which function object is obtained
+ * @return script function for script level expressions
+ */
+ public ScriptFunction getFunction(final Global newGlobal);
+ }
+
+ /**
+ * Compile a top level script.
+ *
+ * @param source the script source
+ * @return reusable compiled script across many global scopes.
+ */
+ public MultiGlobalCompiledScript compileScript(final Source source) {
+ final Class<?> clazz = compile(source, this.errors, this._strict);
+ final MethodHandle runMethodHandle = getRunScriptHandle(clazz);
+ final boolean strict = isStrict(clazz);
+
+ return new MultiGlobalCompiledScript() {
+ @Override
+ public ScriptFunction getFunction(final Global newGlobal) {
+ return Context.getGlobal().newScriptFunction(RUN_SCRIPT.symbolName(), runMethodHandle, newGlobal, strict);
+ }
+ };
+ }
+
+ /**
* Entry point for {@code eval}
*
* @param initialScope The scope of this eval call
@@ -949,14 +982,8 @@
return ScriptRuntime.apply(script, thiz);
}
- private static ScriptFunction getRunScriptFunction(final Class<?> script, final ScriptObject scope) {
- if (script == null) {
- return null;
- }
-
- // Get run method - the entry point to the script
- final MethodHandle runMethodHandle =
- MH.findStatic(
+ private static MethodHandle getRunScriptHandle(final Class<?> script) {
+ return MH.findStatic(
MethodHandles.lookup(),
script,
RUN_SCRIPT.symbolName(),
@@ -964,14 +991,24 @@
Object.class,
ScriptFunction.class,
Object.class));
+ }
- boolean strict;
-
+ private static boolean isStrict(final Class<?> script) {
try {
- strict = script.getField(STRICT_MODE.symbolName()).getBoolean(null);
+ return script.getField(STRICT_MODE.symbolName()).getBoolean(null);
} catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
- strict = false;
+ return false;
}
+ }
+
+ private static ScriptFunction getRunScriptFunction(final Class<?> script, final ScriptObject scope) {
+ if (script == null) {
+ return null;
+ }
+
+ // Get run method - the entry point to the script
+ final MethodHandle runMethodHandle = getRunScriptHandle(script);
+ boolean strict = isStrict(script);
// Package as a JavaScript function and pass function back to shell.
return Context.getGlobal().newScriptFunction(RUN_SCRIPT.symbolName(), runMethodHandle, scope, strict);
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptEnvironment.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptEnvironment.java Mon May 12 09:37:50 2014 -0700
@@ -62,6 +62,9 @@
/** Only compile script, do not run it or generate other ScriptObjects */
public final boolean _compile_only;
+ /** Accept "const" keyword and treat it as variable. Interim feature */
+ public final boolean _const_as_var;
+
/** Accumulated callsite flags that will be used when bootstrapping script callsites */
public final int _callsite_flags;
@@ -200,6 +203,7 @@
_class_cache_size = options.getInteger("class.cache.size");
_compile_only = options.getBoolean("compile.only");
+ _const_as_var = options.getBoolean("const.as.var");
_debug_lines = options.getBoolean("debug.lines");
_dest_dir = options.getString("d");
_dump_on_error = options.getBoolean("doe");
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java Mon May 12 09:37:50 2014 -0700
@@ -91,7 +91,7 @@
*/
public abstract class ScriptObject implements PropertyAccess {
- /** __proto__ special property name */
+ /** __proto__ special property name inside object literals. ES6 draft. */
public static final String PROTO_PROPERTY_NAME = "__proto__";
/** Search fall back routine name for "no such method" */
@@ -130,8 +130,10 @@
/** Indexed array data. */
private ArrayData arrayData;
- static final MethodHandle GETPROTO = findOwnMH("getProto", ScriptObject.class);
- static final MethodHandle SETPROTOCHECK = findOwnMH("setProtoCheck", void.class, Object.class);
+ /** Method handle to retrive prototype of this object */
+ public static final MethodHandle GETPROTO = findOwnMH("getProto", ScriptObject.class);
+ /** Method handle to set prototype of this object */
+ public static final MethodHandle SETPROTOCHECK = findOwnMH("setProtoCheck", void.class, Object.class);
static final MethodHandle MEGAMORPHIC_GET = findOwnMH("megamorphicGet", Object.class, String.class, boolean.class, boolean.class);
static final MethodHandle GLOBALFILTER = findOwnMH("globalFilter", Object.class, Object.class);
@@ -1732,10 +1734,6 @@
MethodHandle methodHandle;
if (find == null) {
- if (PROTO_PROPERTY_NAME.equals(name)) {
- return new GuardedInvocation(GETPROTO, NashornGuards.getScriptObjectGuard());
- }
-
if ("getProp".equals(operator)) {
return noSuchProperty(desc, request);
} else if ("getMethod".equals(operator)) {
@@ -1890,9 +1888,7 @@
return createEmptySetMethod(desc, "property.not.writable", true);
}
} else {
- if (PROTO_PROPERTY_NAME.equals(name)) {
- return new GuardedInvocation(SETPROTOCHECK, NashornGuards.getScriptObjectGuard());
- } else if (! isExtensible()) {
+ if (! isExtensible()) {
return createEmptySetMethod(desc, "object.non.extensible", false);
}
}
--- a/nashorn/src/jdk/nashorn/internal/runtime/regexp/JdkRegExp.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/regexp/JdkRegExp.java Mon May 12 09:37:50 2014 -0700
@@ -46,9 +46,6 @@
/** Java regexp pattern to use for match. We compile to one of these */
private Pattern pattern;
- /** The matcher */
- private RegExpMatcher matcher;
-
/**
* Construct a Regular expression from the given {@code source} and {@code flags} strings.
*
@@ -95,14 +92,7 @@
return null; // never matches or similar, e.g. a[]
}
- RegExpMatcher currentMatcher = this.matcher;
-
- if (currentMatcher == null || matcher.getInput() != str) {
- currentMatcher = new DefaultMatcher(str);
- this.matcher = currentMatcher;
- }
-
- return currentMatcher;
+ return new DefaultMatcher(str);
}
class DefaultMatcher implements RegExpMatcher {
--- a/nashorn/src/jdk/nashorn/internal/runtime/regexp/JoniRegExp.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/regexp/JoniRegExp.java Mon May 12 09:37:50 2014 -0700
@@ -44,9 +44,6 @@
/** Compiled Joni Regex */
private Regex regex;
- /** Matcher */
- private RegExpMatcher matcher;
-
/**
* Construct a Regular expression from the given {@code pattern} and {@code flags} strings.
*
@@ -95,14 +92,7 @@
return null;
}
- RegExpMatcher currentMatcher = this.matcher;
-
- if (currentMatcher == null || input != currentMatcher.getInput()) {
- currentMatcher = new JoniMatcher(input);
- this.matcher = currentMatcher;
- }
-
- return currentMatcher;
+ return new JoniMatcher(input);
}
/**
--- a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/Regex.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/Regex.java Mon May 12 09:37:50 2014 -0700
@@ -131,12 +131,13 @@
this.warnings = null;
}
- public void compile() {
+ public synchronized MatcherFactory compile() {
if (factory == null && analyser != null) {
- Compiler compiler = new ArrayCompiler(analyser);
+ new ArrayCompiler(analyser).compile();
analyser = null; // only do this once
- compiler.compile();
}
+ assert factory != null;
+ return factory;
}
public Matcher matcher(char[] chars) {
@@ -144,8 +145,11 @@
}
public Matcher matcher(char[] chars, int p, int end) {
- compile();
- return factory.create(this, chars, p, end);
+ MatcherFactory matcherFactory = factory;
+ if (matcherFactory == null) {
+ matcherFactory = compile();
+ }
+ return matcherFactory.create(this, chars, p, end);
}
public WarnCallback getWarnings() {
--- a/nashorn/src/jdk/nashorn/internal/runtime/resources/Options.properties Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/resources/Options.properties Mon May 12 09:37:50 2014 -0700
@@ -102,6 +102,13 @@
type=Boolean \
}
+nashorn.option.const.as.var = { \
+ name="--const-as-var", \
+ is_undocumented=true, \
+ desc="Replace 'const' with 'var'.", \
+ type=Boolean \
+}
+
nashorn.option.d = { \
name="--dump-debug-dir", \
short_name="-d", \
--- a/nashorn/src/jdk/nashorn/tools/Shell.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/src/jdk/nashorn/tools/Shell.java Mon May 12 09:37:50 2014 -0700
@@ -453,7 +453,7 @@
}
} finally {
if (globalChanged) {
- Context.setGlobal(global);
+ Context.setGlobal(oldGlobal);
}
}
--- a/nashorn/test/script/basic/JDK-8008448.js Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8008448.js Mon May 12 09:37:50 2014 -0700
@@ -26,6 +26,7 @@
* Ensure that all parseable files can be parsed using parser API.
*
* @test
+ * @option --const-as-var
* @option -scripting
* @run
*/
--- a/nashorn/test/script/basic/JDK-8024120.js Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8024120.js Mon May 12 09:37:50 2014 -0700
@@ -32,10 +32,6 @@
obj.__proto__ = null;
-if (obj.__proto__ !== null || typeof(obj.__proto__) != 'object') {
- fail("obj.__proto__ is expected to be null");
-}
-
var p = Object.getPrototypeOf(obj);
if (p !== null || typeof(p) != 'object') {
fail("Object.getPrototypeOf(obj) is expected to be null");
--- a/nashorn/test/script/basic/JDK-8024174.js Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8024174.js Mon May 12 09:37:50 2014 -0700
@@ -46,6 +46,6 @@
__proto__: null
};
-if (obj2.__proto__ !== null || Object.getPrototypeOf(obj2) !== null) {
+if (Object.getPrototypeOf(obj2) !== null) {
fail("obj2.__proto__ was not set to null inside literal");
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/JDK-8027933.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,38 @@
+/*
+ * 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.
+ */
+
+/**
+ * JDK-8027933: Add const.as.var option
+ *
+ * @test
+ * @option --const-as-var
+ * @run
+ */
+
+const THE_ANSWER = 42;
+print("Answer to all questions: " + THE_ANSWER);
+
+print((function () {
+ const FORTY_TWO = 42;
+ return FORTY_TWO
+})())
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/JDK-8027933.js.EXPECTED Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,2 @@
+Answer to all questions: 42
+42
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/JDK-8041998.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,52 @@
+/*
+ * 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
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * JDK-8041998: RegExp implementation is not thread-safe
+ *
+ * @test
+ * @run
+ */
+
+var Thread = java.lang.Thread;
+
+function run() {
+ var line = 'content-type: text/html';
+ for (var i = 0; i < 300; i++) {
+ Thread.sleep(1);
+ line.split(/: /);
+ }
+ print("done");
+}
+
+var threads = [];
+
+for (var i = 0; i < 4; i++) {
+ var thread = new Thread(run);
+ thread.start();
+ threads.push(thread);
+}
+
+for (var i = 0; i < 4; i++) {
+ threads[i].join();
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/JDK-8041998.js.EXPECTED Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,4 @@
+done
+done
+done
+done
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/JDK-8042364.js Mon May 12 09:37:50 2014 -0700
@@ -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.
+ */
+
+/**
+ * JDK-8042364: Make __proto__ ES6 draft compliant
+ *
+ * @test
+ * @run
+ */
+
+// check for Object.prototype.__proto__ accessor property
+print("Object.prototype has __proto__?",
+ Object.prototype.hasOwnProperty("__proto__"))
+
+var desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__")
+print("descriptor");
+print(JSON.stringify(desc))
+print("getter", desc.get)
+print("setter", desc.set)
+
+// no computed "__proto__" name, only identifier!
+var p = {}
+var obj = {
+ "__proto__" : p
+}
+
+if (Object.getPrototypeOf(obj) === p) {
+ fail("obj has wrong __proto__, allows computed __proto__!")
+}
+
+if (obj.__proto__ !== p) {
+ fail("__proto__ not created as normal property!")
+}
+
+if (Object.getPrototypeOf(obj) !== Object.prototype) {
+ fail("obj has wrong __proto__")
+}
+
+var obj2 = {
+ __proto__: p
+}
+
+if (Object.getPrototypeOf(obj2) !== p) {
+ fail("can't set __proto__ in object literal")
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/JDK-8042364.js.EXPECTED Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,5 @@
+Object.prototype has __proto__? true
+descriptor
+{"configurable":true,"enumerable":false}
+getter function getProto() { [native code] }
+setter function setProto() { [native code] }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/error/JDK-8027933.js Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+/**
+ * JDK-8027933: Add const.as.var option
+ *
+ * @test/compile-error
+ */
+
+// without --const-as-var the following should fail to compile
+const THE_ANSWER = 42;
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/error/JDK-8027933.js.EXPECTED Mon May 12 09:37:50 2014 -0700
@@ -0,0 +1,3 @@
+test/script/error/JDK-8027933.js:31:0 Expected an operand but found const
+const THE_ANSWER = 42;
+^
--- a/nashorn/test/src/jdk/nashorn/internal/codegen/CompilerTest.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/internal/codegen/CompilerTest.java Mon May 12 09:37:50 2014 -0700
@@ -71,6 +71,7 @@
options.set("print.ast", true);
options.set("print.parse", true);
options.set("scripting", true);
+ options.set("const.as.var", true);
final ErrorManager errors = new ErrorManager() {
@Override
--- a/nashorn/test/src/jdk/nashorn/internal/parser/ParserTest.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/internal/parser/ParserTest.java Mon May 12 09:37:50 2014 -0700
@@ -65,6 +65,7 @@
options.set("anon.functions", true);
options.set("parse.only", true);
options.set("scripting", true);
+ options.set("const.as.var", true);
ErrorManager errors = new ErrorManager();
this.context = new Context(options, errors, Thread.currentThread().getContextClassLoader());
--- a/nashorn/test/src/jdk/nashorn/internal/runtime/TrustedScriptEngineTest.java Mon May 05 12:48:07 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/internal/runtime/TrustedScriptEngineTest.java Mon May 12 09:37:50 2014 -0700
@@ -220,4 +220,19 @@
// bar should be visible in default context
assertTrue(e.eval("typeof bar").equals("function"));
}
+
+
+ @Test public void nashornSwallowsConstKeyword() throws Exception {
+ final NashornScriptEngineFactory f = new NashornScriptEngineFactory();
+ final String[] args = new String[] { "--const-as-var" };
+ final ScriptEngine engine = f.getScriptEngine(args);
+
+ final Object ret = engine.eval(""
+ + "(function() {\n"
+ + " const x = 10;\n"
+ + " return x;\n"
+ + "})();"
+ );
+ assertEquals(ret, 10, "Parsed and executed OK");
+ }
}