changeset 2959:4b0fdb9f7cfe

Merge
author lana
date Sat, 25 Sep 2010 12:00:05 -0700
parents 9eb9485ec45b b53f226b1d91
children 7b2b0131fa61 b3a4add96d45 04d9b09dbef9
files make/java/java/FILES_java.gmk src/share/classes/com/sun/media/sound/MidiDeviceReceiver.java src/share/native/java/lang/System.c src/share/native/sun/java2d/cmm/lcms/cmscam97.c src/share/native/sun/java2d/cmm/lcms/cmsmatsh.c src/share/native/sun/java2d/cmm/lcms/icc34.h src/share/native/sun/java2d/cmm/lcms/lcms.h test/java/util/Locale/data/deflocale.exe test/java/util/Locale/data/deflocale.jds3 test/java/util/Locale/data/deflocale.rhel4 test/java/util/Locale/data/deflocale.winvista test/java/util/Locale/data/deflocale.winxp
diffstat 266 files changed, 52549 insertions(+), 29467 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Sat Sep 25 10:21:30 2010 +0800
+++ b/.hgtags	Sat Sep 25 12:00:05 2010 -0700
@@ -82,3 +82,7 @@
 3b0abcb512807bb6f6d27755bc50103211bde6ee jdk7-b105
 b91ef6b60f4e19bf4592c6dd594c9bac62487519 jdk7-b106
 882103f334bb23745d3fd70fb7928c347478b0f4 jdk7-b107
+17a5d84b75610255a3527e8ede1da19c91ba7a7e jdk7-b108
+ab0d3f54a63f2aadfcdd2e14b81f79362ce454e2 jdk7-b109
+176586cd040e4dd17a5ff6e91f72df10d7442453 jdk7-b110
+fb63a2688db807a73e2a3de7d9bab298f1bff0e8 jdk7-b111
--- a/make/common/shared/Compiler-sun.gmk	Sat Sep 25 10:21:30 2010 +0800
+++ b/make/common/shared/Compiler-sun.gmk	Sat Sep 25 12:00:05 2010 -0700
@@ -61,6 +61,7 @@
 # Get compiler version
 _CC_VER :=$(shell $(CC) -V 2>&1 | $(HEAD) -n 1)
 CC_VER  :=$(call GetVersion,"$(_CC_VER)")
+CC_MINORVER  :=$(call MinorVersion,$(CC_VER))
 
 # Name of compilers being used
 COMPILER_VERSION-5.7  = SS10
@@ -69,8 +70,10 @@
 COMPILER_NAME-5.8     = Sun Studio 11
 COMPILER_VERSION-5.9  = SS12
 COMPILER_NAME-5.9     = Sun Studio 12
-COMPILER_VERSION-5.10 = SS13
-COMPILER_NAME-5.10    = Sun Studio 13
+COMPILER_VERSION-5.10 = SS12u1
+COMPILER_NAME-5.10    = Sun Studio 12 Update 1
+COMPILER_VERSION-5.11 = OSS12u2
+COMPILER_NAME-5.11    = Oracle Solaris Studio 12 Update 2
 COMPILER_VERSION      = $(COMPILER_VERSION-$(CC_VER))
 COMPILER_NAME         = $(COMPILER_NAME-$(CC_VER))
 
@@ -112,8 +115,8 @@
   XARCH_OPTION_OLD/64      += -xarch=amd64
   LINT_XARCH_OPTION_OLD/64 += -Xarch=amd64
 endif
-# Pick the options we want based on the compiler being used.
-ifeq ($(shell expr $(CC_VER) \>= 5.9), 1)
+# Pick the options we want based on the compiler being used. (5.9 or newer)
+ifeq ($(shell expr $(CC_MINORVER) \>= 9), 1)
   XARCH_OPTION/32 = $(XARCH_OPTION_NEW/32)
   XARCH_OPTION/64 = $(XARCH_OPTION_NEW/64)
   LINT_XARCH_OPTION/32 = $(LINT_XARCH_OPTION_NEW/32)
--- a/make/common/shared/Defs-versions.gmk	Sat Sep 25 10:21:30 2010 +0800
+++ b/make/common/shared/Defs-versions.gmk	Sat Sep 25 12:00:05 2010 -0700
@@ -120,10 +120,10 @@
   else
     REQUIRED_FREE_SPACE       = 1040000
   endif
-  REQUIRED_COMPILER_NAME      = Sun Studio 12
-  REQUIRED_COMPILER_VERSION   = SS12
+  REQUIRED_COMPILER_NAME      = Sun Studio 12 Update 1
+  REQUIRED_COMPILER_VERSION   = SS12u1
   ifeq ($(CC_VERSION),sun)
-    REQUIRED_CC_VER           = 5.9
+    REQUIRED_CC_VER           = 5.10
   endif
   ifeq ($(CC_VERSION),gcc)
     REQUIRED_CC_VER           = 3.4.3
@@ -145,7 +145,7 @@
     REQUIRED_CC_VER           = 4.3.0
   endif
   ifeq ($(CC_VERSION),sun)
-    REQUIRED_CC_VER           = 5.9
+    REQUIRED_CC_VER           = 5.10
   endif
 endif
 
--- a/make/java/java/FILES_java.gmk	Sat Sep 25 10:21:30 2010 +0800
+++ b/make/java/java/FILES_java.gmk	Sat Sep 25 12:00:05 2010 -0700
@@ -183,10 +183,22 @@
         java/util/MissingFormatWidthException.java \
         java/util/UnknownFormatConversionException.java \
         java/util/UnknownFormatFlagsException.java \
+    java/util/IllformedLocaleException.java \
     java/util/FormatterClosedException.java \
     java/util/ListResourceBundle.java \
         sun/util/EmptyListResourceBundle.java \
     java/util/Locale.java \
+        sun/util/locale/AsciiUtil.java \
+        sun/util/locale/BaseLocale.java \
+        sun/util/locale/Extension.java \
+        sun/util/locale/InternalLocaleBuilder.java \
+        sun/util/locale/LanguageTag.java \
+        sun/util/locale/LocaleExtensions.java \
+        sun/util/locale/LocaleObjectCache.java \
+        sun/util/locale/LocaleSyntaxException.java \
+        sun/util/locale/ParseStatus.java \
+        sun/util/locale/StringTokenIterator.java \
+        sun/util/locale/UnicodeLocaleExtension.java \
     java/util/LocaleISOData.java \
         sun/util/LocaleServiceProviderPool.java \
 	sun/util/LocaleDataMetaInfo.java \
--- a/make/java/redist/Makefile	Sat Sep 25 10:21:30 2010 +0800
+++ b/make/java/redist/Makefile	Sat Sep 25 12:00:05 2010 -0700
@@ -43,6 +43,7 @@
 CLIENT_LOCATION = client
 
 DB_SUFFIX = _db
+DTRACE_SUFFIX = _dtrace
 
 ifeq ($(PLATFORM), windows)
   LIB_LOCATION = $(BINDIR)
@@ -56,6 +57,7 @@
 JVMPDB_NAME            = $(LIB_PREFIX)jvm.pdb
 LIBJSIG_NAME           = $(LIB_PREFIX)jsig.$(LIBRARY_SUFFIX)
 JVMDB_NAME             = $(LIB_PREFIX)jvm$(DB_SUFFIX).$(LIBRARY_SUFFIX)
+JVMDTRACE_NAME         = $(LIB_PREFIX)jvm$(DTRACE_SUFFIX).$(LIBRARY_SUFFIX)
 
 CLASSSHARINGDATA_DIR   = $(BUILDDIR)/tools/sharing
 
@@ -161,6 +163,12 @@
 
 ifeq ($(PLATFORM), solaris)
   IMPORT_LIST += $(LIB_LOCATION)/$(SERVER_LOCATION)/$(JVMDB_NAME)
+# The conditional can be removed when import JDKs contain these files.
+ifneq ($(wildcard $(HOTSPOT_SERVER_PATH)/$(JVMDTRACE_NAME)),)
+  IMPORT_LIST += $(LIB_LOCATION)/$(SERVER_LOCATION)/$(JVMDTRACE_NAME)
+else
+  $(warning WARNING: $(HOTSPOT_SERVER_PATH)/$(JVMDB_NAME) not found!)
+endif 
 endif 
 
 ifneq ($(ZERO_BUILD), true)
@@ -171,14 +179,29 @@
 ifeq ($(PLATFORM), solaris)
 #  solaris   vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv  solaris
 
-ifeq ($(ARCH), sparc)
-  IMPORT_LIST += $(LIB_LOCATION)/$(SERVER_LOCATION)/64/$(JVMDB_NAME)
+IMPORT_LIST += $(LIB_LOCATION)/$(CLIENT_LOCATION)/$(JVMDB_NAME)
+
+# The conditional can be removed when import JDKs contain these files.
+ifneq ($(wildcard $(HOTSPOT_CLIENT_PATH)/$(JVMDTRACE_NAME)),)
+  IMPORT_LIST += $(LIB_LOCATION)/$(CLIENT_LOCATION)/$(JVMDTRACE_NAME)
+  IMPORT_LIST += $(LIB_LOCATION)/$(CLIENT_LOCATION)/64/$(JVMDB_NAME)
+  IMPORT_LIST += $(LIB_LOCATION)/$(CLIENT_LOCATION)/64/$(JVMDTRACE_NAME)
+else
+  $(warning WARNING: $(HOTSPOT_CLIENT_PATH)/$(JVMDTRACE_NAME) not found!)
 endif
 
-IMPORT_LIST += $(LIB_LOCATION)/$(CLIENT_LOCATION)/$(JVMDB_NAME)
+# The conditional can be removed when import JDKs contain these files.
+ifneq ($(wildcard $(HOTSPOT_SERVER_PATH)/64/$(JVMDB_NAME)),)
+  IMPORT_LIST += $(LIB_LOCATION)/$(SERVER_LOCATION)/64/$(JVMDB_NAME)
+else
+  $(warning WARNING: $(HOTSPOT_SERVER_PATH)/64/$(JVMDB_NAME) not found!)
+endif
 
-ifeq ($(ARCH), sparc)
-  IMPORT_LIST += $(LIB_LOCATION)/$(CLIENT_LOCATION)/64/$(JVMDB_NAME)
+# The conditional can be removed when import JDKs contain these files.
+ifneq ($(wildcard $(HOTSPOT_SERVER_PATH)/64/$(JVMDTRACE_NAME)),)
+  IMPORT_LIST += $(LIB_LOCATION)/$(SERVER_LOCATION)/64/$(JVMDTRACE_NAME)
+else
+  $(warning WARNING: $(HOTSPOT_SERVER_PATH)/64/$(JVMDTRACE_NAME) not found!)
 endif
 
 # For backwards compatability, make a link of the 32-bit client JVM to $(LIBDIR)
@@ -224,6 +247,18 @@
 $(LIB_LOCATION)/$(SERVER_LOCATION)/64/$(JVMDB_NAME): $(HOTSPOT_SERVER_PATH)/64/$(JVMDB_NAME)
 	$(install-import-file)
 
+$(LIB_LOCATION)/$(CLIENT_LOCATION)/$(JVMDTRACE_NAME): $(HOTSPOT_CLIENT_PATH)/$(JVMDTRACE_NAME)
+	$(install-import-file)
+
+$(LIB_LOCATION)/$(CLIENT_LOCATION)/64/$(JVMDTRACE_NAME): $(HOTSPOT_CLIENT_PATH)/64/$(JVMDTRACE_NAME)
+	$(install-import-file)
+
+$(LIB_LOCATION)/$(SERVER_LOCATION)/$(JVMDTRACE_NAME): $(HOTSPOT_SERVER_PATH)/$(JVMDTRACE_NAME)
+	$(install-import-file)
+
+$(LIB_LOCATION)/$(SERVER_LOCATION)/64/$(JVMDTRACE_NAME): $(HOTSPOT_SERVER_PATH)/64/$(JVMDTRACE_NAME)
+	$(install-import-file)
+
 $(LIB_LOCATION)/$(SERVER_LOCATION)/$(JVM_NAME): $(HOTSPOT_SERVER_PATH)/$(JVM_NAME)
 	$(install-import-file)
 
--- a/make/java/text/base/FILES_java.gmk	Sat Sep 25 10:21:30 2010 +0800
+++ b/make/java/text/base/FILES_java.gmk	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
     java/text/AttributedString.java \
     java/text/BreakDictionary.java \
     java/text/BreakIterator.java \
+    java/text/CalendarBuilder.java \
     java/text/CharacterIterator.java \
     java/text/CharacterIteratorFieldDelegate.java \
     java/text/ChoiceFormat.java \
--- a/make/sun/cmm/lcms/FILES_c_unix.gmk	Sat Sep 25 10:21:30 2010 +0800
+++ b/make/sun/cmm/lcms/FILES_c_unix.gmk	Sat Sep 25 12:00:05 2010 -0700
@@ -25,7 +25,6 @@
 
 FILES_c = \
     cmscam02.c \
-    cmscam97.c \
     cmscgats.c \
     cmscnvrt.c \
     cmserr.c \
@@ -35,13 +34,17 @@
     cmsio0.c \
     cmsio1.c \
     cmslut.c \
-    cmsmatsh.c \
+    cmsmd5.c \
     cmsmtrx.c \
     cmsnamed.c \
+    cmsopt.c \
     cmspack.c \
     cmspcs.c \
+    cmsplugin.c \
     cmsps2.c \
     cmssamp.c \
+    cmssm.c \
+    cmstypes.c \
     cmsvirt.c \
     cmswtpnt.c \
     cmsxform.c \
--- a/make/sun/cmm/lcms/FILES_c_windows.gmk	Sat Sep 25 10:21:30 2010 +0800
+++ b/make/sun/cmm/lcms/FILES_c_windows.gmk	Sat Sep 25 12:00:05 2010 -0700
@@ -25,7 +25,6 @@
 
 FILES_c = \
     cmscam02.c \
-    cmscam97.c \
     cmscgats.c \
     cmscnvrt.c \
     cmserr.c \
@@ -35,13 +34,17 @@
     cmsio0.c \
     cmsio1.c \
     cmslut.c \
-    cmsmatsh.c \
+    cmsmd5.c \
     cmsmtrx.c \
     cmsnamed.c \
+    cmsopt.c \
     cmspack.c \
     cmspcs.c \
+    cmsplugin.c \
     cmsps2.c \
     cmssamp.c \
+    cmssm.c \
+    cmstypes.c \
     cmsvirt.c \
     cmswtpnt.c \
     cmsxform.c \
--- a/make/sun/cmm/lcms/Makefile	Sat Sep 25 10:21:30 2010 +0800
+++ b/make/sun/cmm/lcms/Makefile	Sat Sep 25 12:00:05 2010 -0700
@@ -80,8 +80,8 @@
 vpath %.c   $(SHARE_SRC)/native/sun/java2d
 
 ifeq ($(PLATFORM), windows)
-
-OTHER_LDLIBS = user32.lib version.lib $(OBJDIR)/../../../sun.awt/awt/$(OBJDIRNAME)/awt.lib
+OTHER_CFLAGS += -DCMS_IS_WINDOWS_ -Dsqrtf=sqrt
+OTHER_LDLIBS = $(OBJDIR)/../../../sun.awt/awt/$(OBJDIRNAME)/awt.lib
 OTHER_INCLUDES += -I$(SHARE_SRC)/native/sun/java2d \
                   -I$(SHARE_SRC)/native/sun/awt/debug
 
--- a/make/templates/gpl-cp-header	Sat Sep 25 10:21:30 2010 +0800
+++ b/make/templates/gpl-cp-header	Sat Sep 25 12:00:05 2010 -0700
@@ -17,6 +17,6 @@
 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
-CA 95054 USA or visit www.sun.com if you need additional information or
-have any questions.
+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.
--- a/make/templates/gpl-header	Sat Sep 25 10:21:30 2010 +0800
+++ b/make/templates/gpl-header	Sat Sep 25 12:00:05 2010 -0700
@@ -15,6 +15,6 @@
 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
-CA 95054 USA or visit www.sun.com if you need additional information or
-have any questions.
+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.
--- a/src/share/classes/com/sun/java/swing/SwingUtilities3.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/java/swing/SwingUtilities3.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,13 +31,14 @@
 import java.util.Map;
 import java.util.WeakHashMap;
 import java.util.concurrent.Callable;
+import java.applet.Applet;
 import java.awt.AWTEvent;
 import java.awt.EventQueue;
 import java.awt.Component;
 import java.awt.Container;
+import java.awt.Window;
 import javax.swing.JComponent;
 import javax.swing.RepaintManager;
-import javax.swing.SwingUtilities;
 
 /**
  * A collection of utility methods for Swing.
@@ -91,7 +92,7 @@
      */
     public static void setVsyncRequested(Container rootContainer,
                                          boolean isRequested) {
-        assert SwingUtilities.getRoot(rootContainer) == rootContainer;
+        assert (rootContainer instanceof Applet) || (rootContainer instanceof Window);
         if (isRequested) {
             vsyncedMap.put(rootContainer, Boolean.TRUE);
         } else {
@@ -106,7 +107,7 @@
      * @return {@code true} if vsync painting is requested for {@code rootContainer}
      */
     public static boolean isVsyncRequested(Container rootContainer) {
-        assert SwingUtilities.getRoot(rootContainer) == rootContainer;
+        assert (rootContainer instanceof Applet) || (rootContainer instanceof Window);
         return Boolean.TRUE == vsyncedMap.get(rootContainer);
     }
 
--- a/src/share/classes/com/sun/java/swing/plaf/gtk/GTKPainter.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/java/swing/plaf/gtk/GTKPainter.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -399,7 +399,7 @@
         }
 
         String detail = "arrow";
-        if (name == "ScrollBar.button") {
+        if ((name == "ScrollBar.button") || (name == "TabbedPane.button")) {
             if (arrowType == ArrowType.UP || arrowType == ArrowType.DOWN) {
                 detail = "vscrollbar";
             } else {
@@ -409,7 +409,7 @@
                    name == "Spinner.previousButton") {
             detail = "spinbutton";
         } else if (name != "ComboBox.arrowButton") {
-            assert false;
+            assert false : "unexpected name: " + name;
         }
 
         int gtkState = GTKLookAndFeel.synthStateToGTKState(
@@ -436,7 +436,7 @@
         String name = button.getName();
         String detail = "button";
         int direction = SwingConstants.CENTER;
-        if (name == "ScrollBar.button") {
+        if ((name == "ScrollBar.button") || (name == "TabbedPane.button")) {
             Integer prop = (Integer)
                 button.getClientProperty("__arrow_direction__");
             direction = (prop != null) ?
@@ -457,7 +457,7 @@
         } else if (name == "Spinner.nextButton") {
             detail = "spinbutton_up";
         } else if (name != "ComboBox.arrowButton") {
-            assert false;
+            assert false : "unexpected name: " + name;
         }
 
         int state = context.getComponentState();
--- a/src/share/classes/com/sun/java/swing/plaf/gtk/PangoFonts.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/java/swing/plaf/gtk/PangoFonts.java	Sat Sep 25 12:00:05 2010 -0700
@@ -150,11 +150,6 @@
          * case for it to be a problem the values would have to be different.
          * It also seems unlikely to arise except when a user explicitly
          * deletes the X resource database entry.
-         * 3) Because of rounding errors sizes may differ very slightly
-         * between JDK and GTK. To fix that would at the very least require
-         * Swing to specify floating pt font sizes.
-         * Eg "10 pts" for GTK at 96 dpi to get the same size at Java 2D's
-         * 72 dpi you'd need to specify exactly 13.33.
          * There also some other issues to be aware of for the future:
          * GTK specifies the Xft.dpi value as server-wide which when used
          * on systems with 2 distinct X screens with different physical DPI
@@ -197,11 +192,16 @@
         String fcFamilyLC = family.toLowerCase();
         if (FontUtilities.mapFcName(fcFamilyLC) != null) {
             /* family is a Fc/Pango logical font which we need to expand. */
-           return FontUtilities.getFontConfigFUIR(fcFamilyLC, style, size);
+            Font font =  FontUtilities.getFontConfigFUIR(fcFamilyLC, style, size);
+            font = font.deriveFont(style, (float)dsize);
+            return new FontUIResource(font);
         } else {
             /* It's a physical font which we will create with a fallback */
-            Font font = new FontUIResource(family, style, size);
-            return FontUtilities.getCompositeFontUIResource(font);
+            Font font = new Font(family, style, size);
+            /* a roundabout way to set the font size in floating points */
+            font = font.deriveFont(style, (float)dsize);
+            FontUIResource fuir = new FontUIResource(font);
+            return FontUtilities.getCompositeFontUIResource(fuir);
         }
     }
 
--- a/src/share/classes/com/sun/java/swing/plaf/motif/MotifBorders.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/java/swing/plaf/motif/MotifBorders.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,8 +40,6 @@
 import java.awt.Point;
 import java.awt.Rectangle;
 
-import java.io.Serializable;
-
 /**
  * Factory object that can vend Icons appropriate for the basic L & F.
  * <p>
@@ -99,7 +97,7 @@
         }
 
         public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
-            if (((JComponent)c).hasFocus()) {
+            if (c.hasFocus()) {
                 g.setColor(focus);
                 g.drawRect(x, y, w-1, h-1);
             } else {
@@ -233,6 +231,9 @@
         }
 
         public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
+            if (!(c instanceof JMenuBar)) {
+                return;
+            }
             JMenuBar menuBar = (JMenuBar)c;
             if (menuBar.isBorderPainted() == true) {
                 // this draws the MenuBar border
@@ -658,6 +659,9 @@
          * @param height the height of the painted border
          */
         public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
+            if (!(c instanceof JPopupMenu)) {
+                return;
+            }
 
             Font origFont = g.getFont();
             Color origColor = g.getColor();
@@ -701,6 +705,9 @@
          * @param insets the object to be reinitialized
          */
         public Insets getBorderInsets(Component c, Insets insets) {
+            if (!(c instanceof JPopupMenu)) {
+                return insets;
+            }
             FontMetrics fm;
             int         descent = 0;
             int         ascent = 16;
--- a/src/share/classes/com/sun/java/swing/plaf/windows/WindowsBorders.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/java/swing/plaf/windows/WindowsBorders.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,12 +32,8 @@
 
 import java.awt.Component;
 import java.awt.Insets;
-import java.awt.Dimension;
-import java.awt.Image;
-import java.awt.Rectangle;
 import java.awt.Color;
 import java.awt.Graphics;
-import java.io.Serializable;
 
 import static com.sun.java.swing.plaf.windows.TMSchema.*;
 import static com.sun.java.swing.plaf.windows.XPStyle.Skin;
@@ -159,6 +155,9 @@
 
         public void paintBorder(Component c, Graphics g, int x, int y,
                                 int width, int height) {
+            if (!(c instanceof JToolBar)) {
+                return;
+            }
             g.translate(x, y);
 
             XPStyle xp = XPStyle.getXP();
@@ -190,33 +189,33 @@
 
                 } else {
 
-                if (!vertical) {
-                    if (c.getComponentOrientation().isLeftToRight()) {
+                    if (!vertical) {
+                        if (c.getComponentOrientation().isLeftToRight()) {
+                            g.setColor(shadow);
+                            g.drawLine(4, 3, 4, height - 4);
+                            g.drawLine(4, height - 4, 2, height - 4);
+
+                            g.setColor(highlight);
+                            g.drawLine(2, 3, 3, 3);
+                            g.drawLine(2, 3, 2, height - 5);
+                        } else {
+                            g.setColor(shadow);
+                            g.drawLine(width - 3, 3, width - 3, height - 4);
+                            g.drawLine(width - 4, height - 4, width - 4, height - 4);
+
+                            g.setColor(highlight);
+                            g.drawLine(width - 5, 3, width - 4, 3);
+                            g.drawLine(width - 5, 3, width - 5, height - 5);
+                        }
+                    } else { // Vertical
                         g.setColor(shadow);
-                        g.drawLine(4, 3, 4, height - 4);
-                        g.drawLine(4, height - 4, 2, height - 4);
+                        g.drawLine(3, 4, width - 4, 4);
+                        g.drawLine(width - 4, 2, width - 4, 4);
 
                         g.setColor(highlight);
-                        g.drawLine(2, 3, 3, 3);
-                        g.drawLine(2, 3, 2, height - 5);
-                    } else {
-                        g.setColor(shadow);
-                        g.drawLine(width - 3, 3, width - 3, height - 4);
-                        g.drawLine(width - 4, height - 4, width - 4, height - 4);
-
-                        g.setColor(highlight);
-                        g.drawLine(width - 5, 3, width - 4, 3);
-                        g.drawLine(width - 5, 3, width - 5, height - 5);
+                        g.drawLine(3, 2, width - 4, 2);
+                        g.drawLine(3, 2, 3, 3);
                     }
-                } else { // Vertical
-                    g.setColor(shadow);
-                    g.drawLine(3, 4, width - 4, 4);
-                    g.drawLine(width - 4, 2, width - 4, 4);
-
-                    g.setColor(highlight);
-                    g.drawLine(3, 2, width - 4, 2);
-                    g.drawLine(3, 2, 3, 3);
-                }
                 }
             }
 
@@ -225,6 +224,9 @@
 
         public Insets getBorderInsets(Component c, Insets insets) {
             insets.set(1,1,1,1);
+            if (!(c instanceof JToolBar)) {
+                return insets;
+            }
             if (((JToolBar)c).isFloatable()) {
                 int gripInset = (XPStyle.getXP() != null) ? 12 : 9;
                 if (((JToolBar)c).getOrientation() == HORIZONTAL) {
--- a/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java	Sat Sep 25 12:00:05 2010 -0700
@@ -474,7 +474,7 @@
         This is necessary for Receivers retrieved via MidiSystem.getReceiver()
         (which opens the device implicitely).
      */
-    protected abstract class AbstractReceiver implements Receiver {
+    protected abstract class AbstractReceiver implements MidiDeviceReceiver {
         private boolean open = true;
 
 
@@ -508,6 +508,10 @@
             AbstractMidiDevice.this.closeInternal(this);
         }
 
+        public MidiDevice getMidiDevice() {
+            return AbstractMidiDevice.this;
+        }
+
         protected boolean isOpen() {
             return open;
         }
@@ -529,7 +533,7 @@
      * Also, it has some optimizations regarding sending to the Receivers,
      * for known Receivers, and managing itself in the TransmitterList.
      */
-    protected class BasicTransmitter implements Transmitter {
+    protected class BasicTransmitter implements MidiDeviceTransmitter {
 
         private Receiver receiver = null;
         TransmitterList tlist = null;
@@ -568,6 +572,9 @@
             }
         }
 
+        public MidiDevice getMidiDevice() {
+            return AbstractMidiDevice.this;
+        }
 
     } // class BasicTransmitter
 
--- a/src/share/classes/com/sun/media/sound/AudioFloatConverter.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/AudioFloatConverter.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,8 +40,6 @@
  */
 public abstract class AudioFloatConverter {
 
-    public static final Encoding PCM_FLOAT = new Encoding("PCM_FLOAT");
-
     /***************************************************************************
      *
      * LSB Filter, used filter least significant byte in samples arrays.
@@ -982,7 +980,7 @@
                             format.getSampleSizeInBits() + 7) / 8) - 4);
                 }
             }
-        } else if (format.getEncoding().equals(PCM_FLOAT)) {
+        } else if (format.getEncoding().equals(Encoding.PCM_FLOAT)) {
             if (format.getSampleSizeInBits() == 32) {
                 if (format.isBigEndian())
                     conv = new AudioFloatConversion32B();
--- a/src/share/classes/com/sun/media/sound/AudioFloatFormatConverter.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/AudioFloatFormatConverter.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
  * 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,6 @@
                 for (int c = 0; c < targetChannels; c++) {
                     for (int i = 0, ix = off + c; i < len2; i++, ix += cs) {
                         b[ix] = conversion_buffer[i];
-                        ;
                     }
                 }
             } else if (targetChannels == 1) {
@@ -186,7 +185,6 @@
                 for (int c = 1; c < sourceChannels; c++) {
                     for (int i = c, ix = off; i < len2; i += cs, ix++) {
                         b[ix] += conversion_buffer[i];
-                        ;
                     }
                 }
                 float vol = 1f / ((float) sourceChannels);
@@ -390,6 +388,7 @@
                 return -1;
             if (len < 0)
                 return 0;
+            int offlen = off + len;
             int remain = len / nrofchannels;
             int destPos = 0;
             int in_end = ibuffer_len;
@@ -423,7 +422,7 @@
             for (int c = 0; c < nrofchannels; c++) {
                 int ix = 0;
                 float[] buff = cbuffer[c];
-                for (int i = c; i < b.length; i += nrofchannels) {
+                for (int i = c + off; i < offlen; i += nrofchannels) {
                     b[i] = buff[ix++];
                 }
             }
@@ -447,7 +446,7 @@
         }
 
         public long skip(long len) throws IOException {
-            if (len > 0)
+            if (len < 0)
                 return 0;
             if (skipbuffer == null)
                 skipbuffer = new float[1024 * targetFormat.getFrameSize()];
@@ -470,7 +469,7 @@
     }
 
     private Encoding[] formats = { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
-            AudioFloatConverter.PCM_FLOAT };
+            Encoding.PCM_FLOAT };
 
     public AudioInputStream getAudioInputStream(Encoding targetEncoding,
             AudioInputStream sourceStream) {
@@ -482,7 +481,7 @@
         float samplerate = format.getSampleRate();
         int bits = format.getSampleSizeInBits();
         boolean bigendian = format.isBigEndian();
-        if (targetEncoding.equals(AudioFloatConverter.PCM_FLOAT))
+        if (targetEncoding.equals(Encoding.PCM_FLOAT))
             bits = 32;
         AudioFormat targetFormat = new AudioFormat(encoding, samplerate, bits,
                 channels, channels * bits / 8, samplerate, bigendian);
@@ -521,19 +520,19 @@
 
     public Encoding[] getSourceEncodings() {
         return new Encoding[] { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
-                AudioFloatConverter.PCM_FLOAT };
+                Encoding.PCM_FLOAT };
     }
 
     public Encoding[] getTargetEncodings() {
         return new Encoding[] { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
-                AudioFloatConverter.PCM_FLOAT };
+                Encoding.PCM_FLOAT };
     }
 
     public Encoding[] getTargetEncodings(AudioFormat sourceFormat) {
         if (AudioFloatConverter.getConverter(sourceFormat) == null)
             return new Encoding[0];
         return new Encoding[] { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
-                AudioFloatConverter.PCM_FLOAT };
+                Encoding.PCM_FLOAT };
     }
 
     public AudioFormat[] getTargetFormats(Encoding targetEncoding,
@@ -572,17 +571,17 @@
             }
         }
 
-        if (targetEncoding.equals(AudioFloatConverter.PCM_FLOAT)) {
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+        if (targetEncoding.equals(Encoding.PCM_FLOAT)) {
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4,
                     AudioSystem.NOT_SPECIFIED, false));
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4,
                     AudioSystem.NOT_SPECIFIED, true));
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8,
                     AudioSystem.NOT_SPECIFIED, false));
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8,
                     AudioSystem.NOT_SPECIFIED, true));
         }
--- a/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java	Sat Sep 25 12:00:05 2010 -0700
@@ -42,11 +42,14 @@
      */
     public AudioSynthesizerPropertyInfo(String name, Object value) {
         this.name = name;
-        this.value = value;
         if (value instanceof Class)
             valueClass = (Class)value;
-        else if (value != null)
-            valueClass = value.getClass();
+        else
+        {
+            this.value = value;
+            if (value != null)
+                valueClass = value.getClass();
+        }
     }
     /**
      * The name of the property.
--- a/src/share/classes/com/sun/media/sound/DLSSoundbank.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/DLSSoundbank.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -781,7 +781,7 @@
                     }
                     if (sampleformat == 3) {
                         audioformat = new AudioFormat(
-                                AudioFloatConverter.PCM_FLOAT, samplerate, bits,
+                                Encoding.PCM_FLOAT, samplerate, bits,
                                 channels, framesize, samplerate, false);
                     }
 
@@ -965,7 +965,7 @@
             sampleformat = 1;
         else if (audioformat.getEncoding().equals(Encoding.PCM_SIGNED))
             sampleformat = 1;
-        else if (audioformat.getEncoding().equals(AudioFloatConverter.PCM_FLOAT))
+        else if (audioformat.getEncoding().equals(Encoding.PCM_FLOAT))
             sampleformat = 3;
 
         fmt_chunk.writeUnsignedShort(sampleformat);
--- a/src/share/classes/com/sun/media/sound/MidiDeviceReceiver.java	Sat Sep 25 10:21:30 2010 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
- * 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.media.sound;
-
-import javax.sound.midi.MidiDevice;
-import javax.sound.midi.Receiver;
-
-/**
- * A Receiver with reference to it's MidiDevice object.
- *
- * @author Karl Helgason
- */
-public interface MidiDeviceReceiver extends Receiver {
-
-    /** Obtains the MidiDevice object associated with this Receiver.
-     */
-    public MidiDevice getMidiDevice();
-
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/media/sound/MidiDeviceReceiverEnvelope.java	Sat Sep 25 12:00:05 2010 -0700
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * 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.media.sound;
+
+import javax.sound.midi.*;
+
+
+/**
+ * Helper class which allows to convert {@code Receiver}
+ * to {@code MidiDeviceReceiver}.
+ *
+ * @author Alex Menkov
+ */
+public class MidiDeviceReceiverEnvelope implements MidiDeviceReceiver {
+
+    private final MidiDevice device;
+    private final Receiver receiver;
+
+    /**
+     * Creates a new {@code MidiDeviceReceiverEnvelope} object which
+     * envelops the specified {@code Receiver}
+     * and is owned by the specified {@code MidiDevice}.
+     *
+     * @param device the owner {@code MidiDevice}
+     * @param receiver the {@code Receiver} to be enveloped
+     */
+    public MidiDeviceReceiverEnvelope(MidiDevice device, Receiver receiver) {
+        if (device == null || receiver == null) {
+            throw new NullPointerException();
+        }
+        this.device = device;
+        this.receiver = receiver;
+    }
+
+    // Receiver implementation
+    public void close() {
+        receiver.close();
+    }
+
+    public void send(MidiMessage message, long timeStamp) {
+        receiver.send(message, timeStamp);
+    }
+
+    // MidiDeviceReceiver implementation
+    public MidiDevice getMidiDevice() {
+        return device;
+    }
+
+    /**
+     * Obtains the receiver enveloped
+     * by this {@code MidiDeviceReceiverEnvelope} object.
+     *
+     * @return the enveloped receiver
+     */
+    public Receiver getReceiver() {
+        return receiver;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/media/sound/MidiDeviceTransmitterEnvelope.java	Sat Sep 25 12:00:05 2010 -0700
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * 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.media.sound;
+
+import javax.sound.midi.*;
+
+
+/**
+ * Helper class which allows to convert {@code Transmitter}
+ * to {@code MidiDeviceTransmitter}.
+ *
+ * @author Alex Menkov
+ */
+public class MidiDeviceTransmitterEnvelope implements MidiDeviceTransmitter {
+
+    private final MidiDevice device;
+    private final Transmitter transmitter;
+
+    /**
+     * Creates a new {@code MidiDeviceTransmitterEnvelope} object which
+     * envelops the specified {@code Transmitter}
+     * and is owned by the specified {@code MidiDevice}.
+     *
+     * @param device the owner {@code MidiDevice}
+     * @param transmitter the {@code Transmitter} to be enveloped
+     */
+    public MidiDeviceTransmitterEnvelope(MidiDevice device, Transmitter transmitter) {
+        if (device == null || transmitter == null) {
+            throw new NullPointerException();
+        }
+        this.device = device;
+        this.transmitter = transmitter;
+    }
+
+    // Transmitter implementation
+    public void setReceiver(Receiver receiver) {
+        transmitter.setReceiver(receiver);
+    }
+
+    public Receiver getReceiver() {
+        return transmitter.getReceiver();
+    }
+
+    public void close() {
+        transmitter.close();
+    }
+
+
+    // MidiDeviceReceiver implementation
+    public MidiDevice getMidiDevice() {
+        return device;
+    }
+
+    /**
+     * Obtains the transmitter enveloped
+     * by this {@code MidiDeviceTransmitterEnvelope} object.
+     *
+     * @return the enveloped transmitter
+     */
+    public Transmitter getTransmitter() {
+        return transmitter;
+    }
+}
--- a/src/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java	Sat Sep 25 12:00:05 2010 -0700
@@ -205,7 +205,8 @@
         }
         if (buffer.array() == null) {
             return AudioFloatInputStream.getInputStream(new AudioInputStream(
-                    buffer.getInputStream(), format, buffer.capacity()));
+                    buffer.getInputStream(), format,
+                    buffer.capacity() / format.getFrameSize()));
         }
         if (buffer8 != null) {
             if (format.getEncoding().equals(Encoding.PCM_SIGNED)
--- a/src/share/classes/com/sun/media/sound/ModelInstrument.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/ModelInstrument.java	Sat Sep 25 12:00:05 2010 -0700
@@ -56,7 +56,7 @@
 
     public ModelDirector getDirector(ModelPerformer[] performers,
             MidiChannel channel, ModelDirectedPlayer player) {
-        return new ModelStandardDirector(performers, player);
+        return new ModelStandardIndexedDirector(performers, player);
     }
 
     public ModelPerformer[] getPerformers() {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/media/sound/ModelStandardIndexedDirector.java	Sat Sep 25 12:00:05 2010 -0700
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * 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.media.sound;
+
+/**
+ * A standard indexed director who chooses performers
+ * by there keyfrom,keyto,velfrom,velto properties.
+ *
+ * @author Karl Helgason
+ */
+public class ModelStandardIndexedDirector implements ModelDirector {
+
+    ModelPerformer[] performers;
+    ModelDirectedPlayer player;
+    boolean noteOnUsed = false;
+    boolean noteOffUsed = false;
+
+    // Variables needed for index
+    byte[][] trantables;
+    int[] counters;
+    int[][] mat;
+
+    public ModelStandardIndexedDirector(ModelPerformer[] performers,
+            ModelDirectedPlayer player) {
+        this.performers = performers;
+        this.player = player;
+        for (int i = 0; i < performers.length; i++) {
+            ModelPerformer p = performers[i];
+            if (p.isReleaseTriggered()) {
+                noteOffUsed = true;
+            } else {
+                noteOnUsed = true;
+            }
+        }
+        buildindex();
+    }
+
+    private int[] lookupIndex(int x, int y) {
+        if ((x >= 0) && (x < 128) && (y >= 0) && (y < 128)) {
+            int xt = trantables[0][x];
+            int yt = trantables[1][y];
+            if (xt != -1 && yt != -1) {
+                return mat[xt + yt * counters[0]];
+            }
+        }
+        return null;
+    }
+
+    private int restrict(int value) {
+        if(value < 0) return 0;
+        if(value > 127) return 127;
+        return value;
+    }
+
+    private void buildindex() {
+        trantables = new byte[2][129];
+        counters = new int[trantables.length];
+        for (ModelPerformer performer : performers) {
+            int keyFrom = performer.getKeyFrom();
+            int keyTo = performer.getKeyTo();
+            int velFrom = performer.getVelFrom();
+            int velTo = performer.getVelTo();
+            if (keyFrom > keyTo) continue;
+            if (velFrom > velTo) continue;
+            keyFrom = restrict(keyFrom);
+            keyTo = restrict(keyTo);
+            velFrom = restrict(velFrom);
+            velTo = restrict(velTo);
+            trantables[0][keyFrom] = 1;
+            trantables[0][keyTo + 1] = 1;
+            trantables[1][velFrom] = 1;
+            trantables[1][velTo + 1] = 1;
+        }
+        for (int d = 0; d < trantables.length; d++) {
+            byte[] trantable = trantables[d];
+            int transize = trantable.length;
+            for (int i = transize - 1; i >= 0; i--) {
+                if (trantable[i] == 1) {
+                    trantable[i] = -1;
+                    break;
+                }
+                trantable[i] = -1;
+            }
+            int counter = -1;
+            for (int i = 0; i < transize; i++) {
+                if (trantable[i] != 0) {
+                    counter++;
+                    if (trantable[i] == -1)
+                        break;
+                }
+                trantable[i] = (byte) counter;
+            }
+            counters[d] = counter;
+        }
+        mat = new int[counters[0] * counters[1]][];
+        int ix = 0;
+        for (ModelPerformer performer : performers) {
+            int keyFrom = performer.getKeyFrom();
+            int keyTo = performer.getKeyTo();
+            int velFrom = performer.getVelFrom();
+            int velTo = performer.getVelTo();
+            if (keyFrom > keyTo) continue;
+            if (velFrom > velTo) continue;
+            keyFrom = restrict(keyFrom);
+            keyTo = restrict(keyTo);
+            velFrom = restrict(velFrom);
+            velTo = restrict(velTo);
+            int x_from = trantables[0][keyFrom];
+            int x_to = trantables[0][keyTo + 1];
+            int y_from = trantables[1][velFrom];
+            int y_to = trantables[1][velTo + 1];
+            if (x_to == -1)
+                x_to = counters[0];
+            if (y_to == -1)
+                y_to = counters[1];
+            for (int y = y_from; y < y_to; y++) {
+                int i = x_from + y * counters[0];
+                for (int x = x_from; x < x_to; x++) {
+                    int[] mprev = mat[i];
+                    if (mprev == null) {
+                        mat[i] = new int[] { ix };
+                    } else {
+                        int[] mnew = new int[mprev.length + 1];
+                        mnew[mnew.length - 1] = ix;
+                        for (int k = 0; k < mprev.length; k++)
+                            mnew[k] = mprev[k];
+                        mat[i] = mnew;
+                    }
+                    i++;
+                }
+            }
+            ix++;
+        }
+    }
+
+    public void close() {
+    }
+
+    public void noteOff(int noteNumber, int velocity) {
+        if (!noteOffUsed)
+            return;
+        int[] plist = lookupIndex(noteNumber, velocity);
+        if(plist == null) return;
+        for (int i : plist) {
+            ModelPerformer p = performers[i];
+            if (p.isReleaseTriggered()) {
+                player.play(i, null);
+            }
+        }
+    }
+
+    public void noteOn(int noteNumber, int velocity) {
+        if (!noteOnUsed)
+            return;
+        int[] plist = lookupIndex(noteNumber, velocity);
+        if(plist == null) return;
+        for (int i : plist) {
+            ModelPerformer p = performers[i];
+            if (!p.isReleaseTriggered()) {
+                player.play(i, null);
+            }
+        }
+    }
+}
--- a/src/share/classes/com/sun/media/sound/SoftChannel.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/SoftChannel.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -116,7 +116,7 @@
     protected int tuning_program = 0;
     protected SoftInstrument current_instrument = null;
     protected ModelChannelMixer current_mixer = null;
-    private ModelDirector current_director = null;
+    protected ModelDirector current_director = null;
 
     // Controller Destination Settings
     protected int cds_control_number = -1;
@@ -1264,13 +1264,16 @@
     }
 
     public void programChange(int bank, int program) {
-        bank = restrict7Bit(bank);
+        bank = restrict14Bit(bank);
         program = restrict7Bit(program);
         synchronized (control_mutex) {
             mainmixer.activity();
-            this.bank = bank;
-            this.program = program;
-            current_instrument = null;
+            if(this.bank != bank || this.program != program)
+            {
+                this.bank = bank;
+                this.program = program;
+                current_instrument = null;
+            }
         }
     }
 
--- a/src/share/classes/com/sun/media/sound/SoftMixingMixer.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/SoftMixingMixer.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -118,16 +118,16 @@
                         AudioSystem.NOT_SPECIFIED, bits, channels, channels
                                 * bits / 8, AudioSystem.NOT_SPECIFIED, true));
             }
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4,
                     AudioSystem.NOT_SPECIFIED, false));
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4,
                     AudioSystem.NOT_SPECIFIED, true));
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8,
                     AudioSystem.NOT_SPECIFIED, false));
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8,
                     AudioSystem.NOT_SPECIFIED, true));
         }
--- a/src/share/classes/com/sun/media/sound/SoftReceiver.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/SoftReceiver.java	Sat Sep 25 12:00:05 2010 -0700
@@ -27,6 +27,7 @@
 import java.util.TreeMap;
 
 import javax.sound.midi.MidiDevice;
+import javax.sound.midi.MidiDeviceReceiver;
 import javax.sound.midi.MidiMessage;
 import javax.sound.midi.ShortMessage;
 
--- a/src/share/classes/com/sun/media/sound/SoftSynthesizer.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/SoftSynthesizer.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,16 +25,25 @@
 
 package com.sun.media.sound;
 
+import java.io.BufferedInputStream;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.OutputStream;
 import java.lang.ref.WeakReference;
-import java.security.AccessControlException;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Properties;
+import java.util.StringTokenizer;
+import java.util.prefs.BackingStoreException;
+import java.util.prefs.Preferences;
 
 import javax.sound.midi.Instrument;
 import javax.sound.midi.MidiChannel;
@@ -182,6 +191,7 @@
     // 1: DLS Voice Allocation
     protected int voice_allocation_mode = 0;
 
+    protected boolean load_default_soundbank = false;
     protected boolean reverb_light = true;
     protected boolean reverb_on = true;
     protected boolean chorus_on = true;
@@ -226,8 +236,6 @@
             = new HashMap<String, SoftTuning>();
     private Map<String, SoftInstrument> inslist
             = new HashMap<String, SoftInstrument>();
-    private Map<String, ModelInstrument> availlist
-            = new HashMap<String, ModelInstrument>();
     private Map<String, ModelInstrument> loadedlist
             = new HashMap<String, ModelInstrument>();
 
@@ -275,10 +283,12 @@
         synchronized (control_mutex) {
             if (channels != null)
                 for (SoftChannel c : channels)
+                {
                     c.current_instrument = null;
+                    c.current_director = null;
+                }
             for (Instrument instrument : instruments) {
                 String pat = patchToString(instrument.getPatch());
-                availlist.remove(pat);
                 SoftInstrument softins
                         = new SoftInstrument((ModelInstrument) instrument);
                 inslist.put(pat, softins);
@@ -341,6 +351,7 @@
         number_of_midi_channels = (Integer)items[10].value;
         jitter_correction = (Boolean)items[11].value;
         reverb_light = (Boolean)items[12].value;
+        load_default_soundbank = (Boolean)items[13].value;
     }
 
     private String patchToString(Patch patch) {
@@ -578,7 +589,9 @@
                 c.current_instrument = null;
             inslist.remove(pat);
             loadedlist.remove(pat);
-            availlist.remove(pat);
+            for (int i = 0; i < channels.length; i++) {
+                channels[i].allSoundOff();
+            }
         }
     }
 
@@ -600,7 +613,7 @@
             return false;
 
         synchronized (control_mutex) {
-            if (!loadedlist.containsValue(to) && !availlist.containsValue(to))
+            if (!loadedlist.containsValue(to))
                 throw new IllegalArgumentException("Instrument to is not loaded.");
             unloadInstrument(from);
             ModelMappedInstrument mfrom = new ModelMappedInstrument(
@@ -609,118 +622,155 @@
         }
     }
 
-    public synchronized Soundbank getDefaultSoundbank() {
-        if (defaultSoundBank == null) {
-            try {
-                File javahome = new File(System.getProperties().getProperty(
-                        "java.home"));
-                File libaudio = new File(new File(javahome, "lib"), "audio");
+    public Soundbank getDefaultSoundbank() {
+        synchronized (SoftSynthesizer.class) {
+            if (defaultSoundBank != null)
+                return defaultSoundBank;
 
-                if (libaudio.exists()) {
-                    File foundfile = null;
-                    File[] files = libaudio.listFiles();
-                    if (files != null) {
-                        for (int i = 0; i < files.length; i++) {
-                            File file = files[i];
-                            if (file.isFile()) {
-                                String lname = file.getName().toLowerCase();
-                                if (lname.endsWith(".sf2") ||
-                                        lname.endsWith(".dls")) {
-                                    if (foundfile == null || (file.length() >
-                                            foundfile.length())) {
-                                        foundfile = file;
+            List<PrivilegedAction<InputStream>> actions =
+                new ArrayList<PrivilegedAction<InputStream>>();
+
+            actions.add(new PrivilegedAction<InputStream>() {
+                public InputStream run() {
+                    File javahome = new File(System.getProperties()
+                            .getProperty("java.home"));
+                    File libaudio = new File(new File(javahome, "lib"), "audio");
+                    if (libaudio.exists()) {
+                        File foundfile = null;
+                        File[] files = libaudio.listFiles();
+                        if (files != null) {
+                            for (int i = 0; i < files.length; i++) {
+                                File file = files[i];
+                                if (file.isFile()) {
+                                    String lname = file.getName().toLowerCase();
+                                    if (lname.endsWith(".sf2")
+                                            || lname.endsWith(".dls")) {
+                                        if (foundfile == null
+                                                || (file.length() > foundfile
+                                                        .length())) {
+                                            foundfile = file;
+                                        }
                                     }
                                 }
                             }
                         }
-                    }
-                    if (foundfile != null) {
-                        try {
-                            Soundbank sbk = MidiSystem.getSoundbank(foundfile);
-                            defaultSoundBank = sbk;
-                            return defaultSoundBank;
-                        } catch (Exception e) {
-                            //e.printStackTrace();
+                        if (foundfile != null) {
+                            try {
+                                return new FileInputStream(foundfile);
+                            } catch (IOException e) {
+                            }
                         }
                     }
+                    return null;
                 }
+            });
 
-                if (System.getProperties().getProperty("os.name")
-                        .startsWith("Windows")) {
-                    File gm_dls = new File(System.getenv("SystemRoot")
-                            + "\\system32\\drivers\\gm.dls");
-                    if (gm_dls.exists()) {
-                        try {
-                            Soundbank sbk = MidiSystem.getSoundbank(gm_dls);
-                            defaultSoundBank = sbk;
-                            return defaultSoundBank;
-                        } catch (Exception e) {
-                            //e.printStackTrace();
+            actions.add(new PrivilegedAction<InputStream>() {
+                public InputStream run() {
+                    if (System.getProperties().getProperty("os.name")
+                            .startsWith("Windows")) {
+                        File gm_dls = new File(System.getenv("SystemRoot")
+                                + "\\system32\\drivers\\gm.dls");
+                        if (gm_dls.exists()) {
+                            try {
+                                return new FileInputStream(gm_dls);
+                            } catch (IOException e) {
+                            }
                         }
                     }
+                    return null;
                 }
-            } catch (AccessControlException e) {
-            } catch (Exception e) {
-                //e.printStackTrace();
-            }
+            });
 
-            File userhome = null;
-            File emg_soundbank_file = null;
+            actions.add(new PrivilegedAction<InputStream>() {
+                public InputStream run() {
+                    /*
+                     * Try to load saved generated soundbank
+                     */
+                    File userhome = new File(System.getProperty("user.home"),
+                            ".gervill");
+                    File emg_soundbank_file = new File(userhome,
+                            "soundbank-emg.sf2");
+                    if (emg_soundbank_file.exists()) {
+                        try {
+                            return new FileInputStream(emg_soundbank_file);
+                        } catch (IOException e) {
+                        }
+                    }
+                    return null;
+                }
+            });
 
-            /*
-             *  Try to load saved generated soundbank
-             */
-            try {
-                userhome = new File(System.getProperty("user.home"),
-                     ".gervill");
-                emg_soundbank_file = new File(userhome, "soundbank-emg.sf2");
-                Soundbank sbk = MidiSystem.getSoundbank(emg_soundbank_file);
-                defaultSoundBank = sbk;
-                return defaultSoundBank;
-            } catch (AccessControlException e) {
-            } catch (Exception e) {
-                //e.printStackTrace();
+            for (PrivilegedAction<InputStream> action : actions) {
+                try {
+                    InputStream is = AccessController.doPrivileged(action);
+                    if(is == null) continue;
+                    Soundbank sbk;
+                    try {
+                        sbk = MidiSystem.getSoundbank(new BufferedInputStream(is));
+                    } finally {
+                        is.close();
+                    }
+                    if (sbk != null) {
+                        defaultSoundBank = sbk;
+                        return defaultSoundBank;
+                    }
+                } catch (Exception e) {
+                }
             }
 
             try {
-
                 /*
-                 *  Generate emergency soundbank
+                 * Generate emergency soundbank
                  */
                 defaultSoundBank = EmergencySoundbank.createSoundbank();
-
-                /*
-                 *  Save generated soundbank to disk for faster future use.
-                 */
-                if(defaultSoundBank != null)
-                {
-                    if(!userhome.exists()) userhome.mkdirs();
-                    if(!emg_soundbank_file.exists())
-                        ((SF2Soundbank)defaultSoundBank).save(emg_soundbank_file);
-                }
             } catch (Exception e) {
-                //e.printStackTrace();
             }
 
+            if (defaultSoundBank != null) {
+                /*
+                 * Save generated soundbank to disk for faster future use.
+                 */
+                OutputStream out = AccessController
+                        .doPrivileged(new PrivilegedAction<OutputStream>() {
+                            public OutputStream run() {
+                                try {
+                                    File userhome = new File(System
+                                            .getProperty("user.home"),
+                                            ".gervill");
+                                    if (!userhome.exists())
+                                        userhome.mkdirs();
+                                    File emg_soundbank_file = new File(
+                                            userhome, "soundbank-emg.sf2");
+                                    if (emg_soundbank_file.exists())
+                                        return null;
+                                    return new FileOutputStream(
+                                            emg_soundbank_file);
+                                } catch (IOException e) {
+                                } catch (SecurityException e) {
+                                }
+                                return null;
+                            }
+                        });
+                if (out != null) {
+                    try {
+                        ((SF2Soundbank) defaultSoundBank).save(out);
+                        out.close();
+                    } catch (IOException e) {
+                    }
+                }
+            }
         }
         return defaultSoundBank;
     }
 
     public Instrument[] getAvailableInstruments() {
-        if (!isOpen()) {
-            Soundbank defsbk = getDefaultSoundbank();
-            if (defsbk == null)
-                return new Instrument[0];
-            return defsbk.getInstruments();
-        }
-
-        synchronized (control_mutex) {
-            ModelInstrument[] inslist_array =
-                    new ModelInstrument[availlist.values().size()];
-            availlist.values().toArray(inslist_array);
-            Arrays.sort(inslist_array, new ModelInstrumentComparator());
-            return inslist_array;
-        }
+        Soundbank defsbk = getDefaultSoundbank();
+        if (defsbk == null)
+            return new Instrument[0];
+        Instrument[] inslist_array = defsbk.getInstruments();
+        Arrays.sort(inslist_array, new ModelInstrumentComparator());
+        return inslist_array;
     }
 
     public Instrument[] getLoadedInstruments() {
@@ -794,6 +844,31 @@
         return info;
     }
 
+    private Properties getStoredProperties() {
+        return AccessController
+                .doPrivileged(new PrivilegedAction<Properties>() {
+                    public Properties run() {
+                        Properties p = new Properties();
+                        String notePath = "/com/sun/media/sound/softsynthesizer";
+                        try {
+                            Preferences prefroot = Preferences.userRoot();
+                            if (prefroot.nodeExists(notePath)) {
+                                Preferences prefs = prefroot.node(notePath);
+                                String[] prefs_keys = prefs.keys();
+                                for (String prefs_key : prefs_keys) {
+                                    String val = prefs.get(prefs_key, null);
+                                    if (val != null)
+                                        p.setProperty(prefs_key, val);
+                                }
+                            }
+                        } catch (BackingStoreException e) {
+                        } catch (SecurityException e) {
+                        }
+                        return p;
+                    }
+                });
+    }
+
     public AudioSynthesizerPropertyInfo[] getPropertyInfo(Map<String, Object> info) {
         List<AudioSynthesizerPropertyInfo> list =
                 new ArrayList<AudioSynthesizerPropertyInfo>();
@@ -861,17 +936,92 @@
         item.description = "Turn light reverb mode on or off";
         list.add(item);
 
+        item = new AudioSynthesizerPropertyInfo("load default soundbank", o?load_default_soundbank:true);
+        item.description = "Enabled/disable loading default soundbank";
+        list.add(item);
+
         AudioSynthesizerPropertyInfo[] items;
         items = list.toArray(new AudioSynthesizerPropertyInfo[list.size()]);
 
-        if (info != null)
-            for (AudioSynthesizerPropertyInfo item2: items) {
-                Object v = info.get(item2.name);
+        Properties storedProperties = getStoredProperties();
+
+        for (AudioSynthesizerPropertyInfo item2 : items) {
+            Object v = (info == null) ? null : info.get(item2.name);
+            v = (v != null) ? v : storedProperties.getProperty(item2.name);
+            if (v != null) {
                 Class c = (item2.valueClass);
-                if (v != null)
-                    if (c.isInstance(v))
-                        item2.value = v;
+                if (c.isInstance(v))
+                    item2.value = v;
+                else if (v instanceof String) {
+                    String s = (String) v;
+                    if (c == Boolean.class) {
+                        if (s.equalsIgnoreCase("true"))
+                            item2.value = Boolean.TRUE;
+                        if (s.equalsIgnoreCase("false"))
+                            item2.value = Boolean.FALSE;
+                    } else if (c == AudioFormat.class) {
+                        int channels = 2;
+                        boolean signed = true;
+                        boolean bigendian = false;
+                        int bits = 16;
+                        float sampleRate = 44100f;
+                        try {
+                            StringTokenizer st = new StringTokenizer(s, ", ");
+                            String prevToken = "";
+                            while (st.hasMoreTokens()) {
+                                String token = st.nextToken().toLowerCase();
+                                if (token.equals("mono"))
+                                    channels = 1;
+                                if (token.startsWith("channel"))
+                                    channels = Integer.parseInt(prevToken);
+                                if (token.contains("unsigned"))
+                                    signed = false;
+                                if (token.equals("big-endian"))
+                                    bigendian = true;
+                                if (token.equals("bit"))
+                                    bits = Integer.parseInt(prevToken);
+                                if (token.equals("hz"))
+                                    sampleRate = Float.parseFloat(prevToken);
+                                prevToken = token;
+                            }
+                            item2.value = new AudioFormat(sampleRate, bits,
+                                    channels, signed, bigendian);
+                        } catch (NumberFormatException e) {
+                        }
+
+                    } else
+                        try {
+                            if (c == Byte.class)
+                                item2.value = Byte.valueOf(s);
+                            else if (c == Short.class)
+                                item2.value = Short.valueOf(s);
+                            else if (c == Integer.class)
+                                item2.value = Integer.valueOf(s);
+                            else if (c == Long.class)
+                                item2.value = Long.valueOf(s);
+                            else if (c == Float.class)
+                                item2.value = Float.valueOf(s);
+                            else if (c == Double.class)
+                                item2.value = Double.valueOf(s);
+                        } catch (NumberFormatException e) {
+                        }
+                } else if (v instanceof Number) {
+                    Number n = (Number) v;
+                    if (c == Byte.class)
+                        item2.value = Byte.valueOf(n.byteValue());
+                    if (c == Short.class)
+                        item2.value = Short.valueOf(n.shortValue());
+                    if (c == Integer.class)
+                        item2.value = Integer.valueOf(n.intValue());
+                    if (c == Long.class)
+                        item2.value = Long.valueOf(n.longValue());
+                    if (c == Float.class)
+                        item2.value = Float.valueOf(n.floatValue());
+                    if (c == Double.class)
+                        item2.value = Double.valueOf(n.doubleValue());
+                }
             }
+        }
 
         return items;
     }
@@ -1007,11 +1157,12 @@
             if (targetFormat != null)
                 setFormat(targetFormat);
 
-            Soundbank defbank = getDefaultSoundbank();
-            if (defbank != null) {
-                loadAllInstruments(defbank);
-                availlist.putAll(loadedlist);
-                loadedlist.clear();
+            if (load_default_soundbank)
+            {
+                Soundbank defbank = getDefaultSoundbank();
+                if (defbank != null) {
+                    loadAllInstruments(defbank);
+                }
             }
 
             voices = new SoftVoice[maxpoly];
@@ -1117,7 +1268,6 @@
             }
 
             inslist.clear();
-            availlist.clear();
             loadedlist.clear();
             tunings.clear();
 
--- a/src/share/classes/com/sun/media/sound/SoftVoice.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/SoftVoice.java	Sat Sep 25 12:00:05 2010 -0700
@@ -279,9 +279,12 @@
     }
 
     protected void updateTuning(SoftTuning newtuning) {
+        tuning = newtuning;
         tunedKey = tuning.getTuning(note) / 100.0;
         if (!portamento) {
             co_noteon_keynumber[0] = tunedKey * (1.0 / 128.0);
+            if(performer == null)
+                return;
             int[] c = performer.midi_connections[4];
             if (c == null)
                 return;
@@ -433,6 +436,8 @@
     }
 
     protected void setPolyPressure(int pressure) {
+        if(performer == null)
+            return;
         int[] c = performer.midi_connections[2];
         if (c == null)
             return;
@@ -441,6 +446,8 @@
     }
 
     protected void setChannelPressure(int pressure) {
+        if(performer == null)
+            return;
         int[] c = performer.midi_connections[1];
         if (c == null)
             return;
@@ -449,6 +456,8 @@
     }
 
     protected void controlChange(int controller, int value) {
+        if(performer == null)
+            return;
         int[] c = performer.midi_ctrl_connections[controller];
         if (c == null)
             return;
@@ -457,6 +466,8 @@
     }
 
     protected void nrpnChange(int controller, int value) {
+        if(performer == null)
+            return;
         int[] c = performer.midi_nrpn_connections.get(controller);
         if (c == null)
             return;
@@ -465,6 +476,8 @@
     }
 
     protected void rpnChange(int controller, int value) {
+        if(performer == null)
+            return;
         int[] c = performer.midi_rpn_connections.get(controller);
         if (c == null)
             return;
@@ -473,6 +486,8 @@
     }
 
     protected void setPitchBend(int bend) {
+        if(performer == null)
+            return;
         int[] c = performer.midi_connections[0];
         if (c == null)
             return;
@@ -499,6 +514,8 @@
 
         co_noteon_on[0] = -1;
 
+        if(performer == null)
+            return;
         int[] c = performer.midi_connections[3];
         if (c == null)
             return;
@@ -527,6 +544,8 @@
 
         co_noteon_on[0] = 0;
 
+        if(performer == null)
+            return;
         int[] c = performer.midi_connections[3];
         if (c == null)
             return;
@@ -543,6 +562,8 @@
         sustain = true;
         co_noteon_on[0] = 1;
 
+        if(performer == null)
+            return;
         int[] c = performer.midi_connections[3];
         if (c == null)
             return;
@@ -555,6 +576,11 @@
             active = false;
             stopping = false;
             audiostarted = false;
+            instrument = null;
+            performer = null;
+            connections = null;
+            extendedConnectionBlocks = null;
+            channelmixer = null;
             if (osc_stream != null)
                 try {
                     osc_stream.close();
--- a/src/share/classes/com/sun/media/sound/WaveExtensibleFileReader.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/WaveExtensibleFileReader.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -271,7 +271,7 @@
                         bits, channels, framesize, samplerate, false, p);
             }
         } else if (subFormat.equals(SUBTYPE_IEEE_FLOAT)) {
-            audioformat = new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            audioformat = new AudioFormat(Encoding.PCM_FLOAT,
                     samplerate, bits, channels, framesize, samplerate, false, p);
         } else
             throw new UnsupportedAudioFileException();
--- a/src/share/classes/com/sun/media/sound/WaveFloatFileReader.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/WaveFloatFileReader.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,6 +33,7 @@
 
 import javax.sound.sampled.AudioFileFormat;
 import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioFormat.Encoding;
 import javax.sound.sampled.AudioInputStream;
 import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.UnsupportedAudioFileException;
@@ -102,7 +103,7 @@
             throw new UnsupportedAudioFileException();
 
         AudioFormat audioformat = new AudioFormat(
-                AudioFloatConverter.PCM_FLOAT, samplerate, bits, channels,
+                Encoding.PCM_FLOAT, samplerate, bits, channels,
                 framesize, samplerate, false);
         AudioFileFormat fileformat = new AudioFileFormat(
                 AudioFileFormat.Type.WAVE, audioformat,
--- a/src/share/classes/com/sun/media/sound/WaveFloatFileWriter.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/com/sun/media/sound/WaveFloatFileWriter.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,7 @@
 
 import javax.sound.sampled.AudioFileFormat;
 import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioFormat.Encoding;
 import javax.sound.sampled.AudioInputStream;
 import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.AudioFileFormat.Type;
@@ -48,8 +49,7 @@
 
     public Type[] getAudioFileTypes(AudioInputStream stream) {
 
-        if (!stream.getFormat().getEncoding().equals(
-                AudioFloatConverter.PCM_FLOAT))
+        if (!stream.getFormat().getEncoding().equals(Encoding.PCM_FLOAT))
             return new Type[0];
         return new Type[] { Type.WAVE };
     }
@@ -58,8 +58,7 @@
         if (!Type.WAVE.equals(type))
             throw new IllegalArgumentException("File type " + type
                     + " not supported.");
-        if (!stream.getFormat().getEncoding().equals(
-                AudioFloatConverter.PCM_FLOAT))
+        if (!stream.getFormat().getEncoding().equals(Encoding.PCM_FLOAT))
             throw new IllegalArgumentException("File format "
                     + stream.getFormat() + " not supported.");
     }
--- a/src/share/classes/java/awt/Dialog.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/awt/Dialog.java	Sat Sep 25 12:00:05 2010 -0700
@@ -277,10 +277,8 @@
      */
     String title;
 
-    private transient volatile boolean keepBlockingEDT = false;
-    private transient volatile boolean keepBlockingCT = false;
-
     private transient ModalEventFilter modalFilter;
+    private transient volatile SecondaryLoop secondaryLoop;
 
     /*
      * Indicates that this dialog is being hidden. This flag is set to true at
@@ -1005,12 +1003,6 @@
         super.setVisible(b);
     }
 
-    /**
-    * Stores the app context on which event dispatch thread the dialog
-    * is being shown. Initialized in show(), used in hideAndDisposeHandler()
-    */
-    transient private AppContext showAppContext;
-
    /**
      * Makes the {@code Dialog} visible. If the dialog and/or its owner
      * are not yet displayable, both are made displayable.  The
@@ -1037,39 +1029,18 @@
         if (!isModal()) {
             conditionalShow(null, null);
         } else {
-            // Set this variable before calling conditionalShow(). That
-            // way, if the Dialog is hidden right after being shown, we
-            // won't mistakenly block this thread.
-            keepBlockingEDT = true;
-            keepBlockingCT = true;
-
-            // Store the app context on which this dialog is being shown.
-            // Event dispatch thread of this app context will be sleeping until
-            // we wake it by any event from hideAndDisposeHandler().
-            showAppContext = AppContext.getAppContext();
+            AppContext showAppContext = AppContext.getAppContext();
 
             AtomicLong time = new AtomicLong();
             Component predictedFocusOwner = null;
             try {
                 predictedFocusOwner = getMostRecentFocusOwner();
                 if (conditionalShow(predictedFocusOwner, time)) {
-                    // We have two mechanisms for blocking: 1. If we're on the
-                    // EventDispatchThread, start a new event pump. 2. If we're
-                    // on any other thread, call wait() on the treelock.
-
                     modalFilter = ModalEventFilter.createFilterForDialog(this);
-
-                    final Runnable pumpEventsForFilter = new Runnable() {
-                        public void run() {
-                            EventDispatchThread dispatchThread =
-                                (EventDispatchThread)Thread.currentThread();
-                            dispatchThread.pumpEventsForFilter(new Conditional() {
-                                public boolean evaluate() {
-                                    synchronized (getTreeLock()) {
-                                        return keepBlockingEDT && windowClosingException == null;
-                                    }
-                                }
-                            }, modalFilter);
+                    Conditional cond = new Conditional() {
+                        @Override
+                        public boolean evaluate() {
+                            return windowClosingException == null;
                         }
                     };
 
@@ -1096,44 +1067,10 @@
 
                     modalityPushed();
                     try {
-                        if (EventQueue.isDispatchThread()) {
-                            /*
-                             * dispose SequencedEvent we are dispatching on current
-                             * AppContext, to prevent us from hang.
-                             *
-                             */
-                            // BugId 4531693 (son@sparc.spb.su)
-                            SequencedEvent currentSequencedEvent = KeyboardFocusManager.
-                                getCurrentKeyboardFocusManager().getCurrentSequencedEvent();
-                            if (currentSequencedEvent != null) {
-                                currentSequencedEvent.dispose();
-                            }
-
-                            /*
-                             * Event processing is done inside doPrivileged block so that
-                             * it wouldn't matter even if user code is on the stack
-                             * Fix for BugId 6300270
-                             */
-
-                             AccessController.doPrivileged(new PrivilegedAction() {
-                                     public Object run() {
-                                        pumpEventsForFilter.run();
-                                        return null;
-                                     }
-                             });
-                        } else {
-                            synchronized (getTreeLock()) {
-                                Toolkit.getEventQueue().postEvent(new PeerEvent(this,
-                                                                                pumpEventsForFilter,
-                                                                                PeerEvent.PRIORITY_EVENT));
-                                while (keepBlockingCT && windowClosingException == null) {
-                                    try {
-                                        getTreeLock().wait();
-                                    } catch (InterruptedException e) {
-                                        break;
-                                    }
-                                }
-                            }
+                        EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
+                        secondaryLoop = eventQueue.createSecondaryLoop(cond, modalFilter, 5000);
+                        if (!secondaryLoop.enter()) {
+                            secondaryLoop = null;
                         }
                     } finally {
                         modalityPopped();
@@ -1194,18 +1131,11 @@
             windowClosingException = null;
         }
     }
-    final class WakingRunnable implements Runnable {
-        public void run() {
-            synchronized (getTreeLock()) {
-                keepBlockingCT = false;
-                getTreeLock().notifyAll();
-            }
-        }
-    }
+
     private void hideAndDisposePreHandler() {
         isInHide = true;
         synchronized (getTreeLock()) {
-            if (keepBlockingEDT) {
+            if (secondaryLoop != null) {
                 modalHide();
                 // dialog can be shown and then disposed before its
                 // modal filter is created
@@ -1217,20 +1147,9 @@
         }
     }
     private void hideAndDisposeHandler() {
-        synchronized (getTreeLock()) {
-            if (keepBlockingEDT) {
-                keepBlockingEDT = false;
-                PeerEvent wakingEvent = new PeerEvent(getToolkit(), new WakingRunnable(), PeerEvent.PRIORITY_EVENT);
-                AppContext curAppContext = AppContext.getAppContext();
-                if (showAppContext != curAppContext) {
-                    // Wake up event dispatch thread on which the dialog was
-                    // initially shown
-                    SunToolkit.postEvent(showAppContext, wakingEvent);
-                    showAppContext = null;
-                } else {
-                    Toolkit.getEventQueue().postEvent(wakingEvent);
-                }
-            }
+        if (secondaryLoop != null) {
+            secondaryLoop.exit();
+            secondaryLoop = null;
         }
         isInHide = false;
     }
--- a/src/share/classes/java/awt/EventDispatchThread.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/awt/EventDispatchThread.java	Sat Sep 25 12:00:05 2010 -0700
@@ -113,8 +113,7 @@
         pumpEventsForHierarchy(id, cond, null);
     }
 
-    void pumpEventsForHierarchy(int id, Conditional cond, Component modalComponent)
-    {
+    void pumpEventsForHierarchy(int id, Conditional cond, Component modalComponent) {
         pumpEventsForFilter(id, cond, new HierarchyEventFilter(modalComponent));
     }
 
@@ -124,6 +123,7 @@
 
     void pumpEventsForFilter(int id, Conditional cond, EventFilter filter) {
         addEventFilter(filter);
+        doDispatch = true;
         while (doDispatch && cond.evaluate()) {
             if (isInterrupted() || !pumpOneEventForFilters(id)) {
                 doDispatch = false;
@@ -133,6 +133,7 @@
     }
 
     void addEventFilter(EventFilter filter) {
+        eventLog.finest("adding the event filter: " + filter);
         synchronized (eventFilters) {
             if (!eventFilters.contains(filter)) {
                 if (filter instanceof ModalEventFilter) {
@@ -156,6 +157,7 @@
     }
 
     void removeEventFilter(EventFilter filter) {
+        eventLog.finest("removing the event filter: " + filter);
         synchronized (eventFilters) {
             eventFilters.remove(filter);
         }
--- a/src/share/classes/java/awt/EventQueue.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/awt/EventQueue.java	Sat Sep 25 12:00:05 2010 -0700
@@ -884,6 +884,41 @@
     }
 
     /**
+     * Creates a new {@code secondary loop} associated with this
+     * event queue. Use the {@link SecondaryLoop#enter} and
+     * {@link SecondaryLoop#exit} methods to start and stop the
+     * event loop and dispatch the events from this queue.
+     *
+     * @return secondaryLoop A new secondary loop object, which can
+     *                       be used to launch a new nested event
+     *                       loop and dispatch events from this queue
+     *
+     * @see SecondaryLoop#enter
+     * @see SecondaryLoop#exit
+     *
+     * @since 1.7
+     */
+    public SecondaryLoop createSecondaryLoop() {
+        return createSecondaryLoop(null, null, 0);
+    }
+
+    SecondaryLoop createSecondaryLoop(Conditional cond, EventFilter filter, long interval) {
+        pushPopLock.lock();
+        try {
+            if (nextQueue != null) {
+                // Forward the request to the top of EventQueue stack
+                return nextQueue.createSecondaryLoop(cond, filter, interval);
+            }
+            if (dispatchThread == null) {
+                initDispatchThread();
+            }
+            return new WaitDispatchSupport(dispatchThread, cond, filter, interval);
+        } finally {
+            pushPopLock.unlock();
+        }
+    }
+
+    /**
      * Returns true if the calling thread is
      * {@link Toolkit#getSystemEventQueue the current AWT EventQueue}'s
      * dispatch thread. Use this method to ensure that a particular
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/awt/SecondaryLoop.java	Sat Sep 25 12:00:05 2010 -0700
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.awt;
+
+/**
+ * A helper interface to run the nested event loop.
+ * <p>
+ * Objects that implement this interface are created with the
+ * {@link EventQueue#createSecondaryLoop} method. The interface
+ * provides two methods, {@link enter} and {@link exit},
+ * which can be used to start and stop the event loop.
+ * <p>
+ * When the {@link enter} method is called, the current
+ * thread is blocked until the loop is terminated by the
+ * {@link exit} method. Also, a new event loop is started
+ * on the event dispatch thread, which may or may not be
+ * the current thread. The loop can be terminated on any
+ * thread by calling its {@link exit} method. After the
+ * loop is terminated, the {@code SecondaryLoop} object can
+ * be reused to run a new nested event loop.
+ * <p>
+ * A typical use case of applying this interface is AWT
+ * and Swing modal dialogs. When a modal dialog is shown on
+ * the event dispatch thread, it enters a new secondary loop.
+ * Later, when the dialog is hidden or disposed, it exits
+ * the loop, and the thread continues its execution.
+ * <p>
+ * The following example illustrates a simple use case of
+ * secondary loops:
+ *
+ * <pre>
+ *   SecondaryLoop loop;
+ *
+ *   JButton jButton = new JButton("Button");
+ *   jButton.addActionListener(new ActionListener() {
+ *       {@code @Override}
+ *       public void actionPerformed(ActionEvent e) {
+ *           Toolkit tk = Toolkit.getDefaultToolkit();
+ *           EventQueue eq = tk.getSystemEventQueue();
+ *           loop = eq.createSecondaryLoop();
+ *
+ *           // Spawn a new thread to do the work
+ *           Thread worker = new WorkerThread();
+ *           worker.start();
+ *
+ *           // Enter the loop to block the current event
+ *           // handler, but leave UI responsive
+ *           if (!loop.enter()) {
+ *               // Report an error
+ *           }
+ *       }
+ *   });
+ *
+ *   class WorkerThread extends Thread {
+ *       {@code @Override}
+ *       public void run() {
+ *           // Perform calculations
+ *           doSomethingUseful();
+ *
+ *           // Exit the loop
+ *           loop.exit();
+ *       }
+ *   }
+ * </pre>
+ *
+ * @see Dialog#show
+ * @see EventQueue#createSecondaryLoop
+ * @see Toolkit#getSystemEventQueue
+ *
+ * @author Anton Tarasov, Artem Ananiev
+ *
+ * @since 1.7
+ */
+public interface SecondaryLoop {
+
+    /**
+     * Blocks the execution of the current thread and enters a new
+     * secondary event loop on the event dispatch thread.
+     * <p>
+     * This method can be called by any thread including the event
+     * dispatch thread. This thread will be blocked until the {@link
+     * exit} method is called or the loop is terminated. A new
+     * secondary loop will be created on the event dispatch thread
+     * for dispatching events in either case.
+     * <p>
+     * This method can only start one new event loop at a time per
+     * object. If a secondary event loop has already been started
+     * by this object and is currently still running, this method
+     * returns {@code false} to indicate that it was not successful
+     * in starting a new event loop. Otherwise, this method blocks
+     * the calling thread and later returns {@code true} when the
+     * new event loop is terminated. At such time, this object can
+     * again be used to start another new event loop.
+     *
+     * @return {@code true} after termination of the secondary loop,
+     *         if the secondary loop was started by this call,
+     *         {@code false} otherwise
+     */
+    public boolean enter();
+
+    /**
+     * Unblocks the execution of the thread blocked by the {@link
+     * enter} method and exits the secondary loop.
+     * <p>
+     * This method resumes the thread that called the {@link enter}
+     * method and exits the secondary loop that was created when
+     * the {@link enter} method was invoked.
+     * <p>
+     * Note that if any other secondary loop is started while this
+     * loop is running, the blocked thread will not resume execution
+     * until the nested loop is terminated.
+     * <p>
+     * If this secondary loop has not been started with the {@link
+     * enter} method, or this secondary loop has already finished
+     * with the {@link exit} method, this method returns {@code
+     * false}, otherwise {@code true} is returned.
+     *
+     * @return {@code true} if this loop was previously started and
+     *         has not yet been finished with the {@link exit} method,
+     *         {@code false} otherwise
+     */
+    public boolean exit();
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/awt/WaitDispatchSupport.java	Sat Sep 25 12:00:05 2010 -0700
@@ -0,0 +1,302 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.awt;
+
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import java.security.PrivilegedAction;
+import java.security.AccessController;
+
+import sun.awt.PeerEvent;
+
+import sun.util.logging.PlatformLogger;
+
+/**
+ * This utility class is used to suspend execution on a thread
+ * while still allowing {@code EventDispatchThread} to dispatch events.
+ * The API methods of the class are thread-safe.
+ *
+ * @author Anton Tarasov, Artem Ananiev
+ *
+ * @since 1.7
+ */
+class WaitDispatchSupport implements SecondaryLoop {
+
+    private final static PlatformLogger log =
+        PlatformLogger.getLogger("java.awt.event.WaitDispatchSupport");
+
+    private EventDispatchThread dispatchThread;
+    private EventFilter filter;
+
+    private volatile Conditional extCondition;
+    private volatile Conditional condition;
+
+    private long interval;
+    // Use a shared daemon timer to serve all the WaitDispatchSupports
+    private static Timer timer;
+    // When this WDS expires, we cancel the timer task leaving the
+    // shared timer up and running
+    private TimerTask timerTask;
+
+    private AtomicBoolean keepBlockingEDT = new AtomicBoolean(false);
+    private AtomicBoolean keepBlockingCT = new AtomicBoolean(false);
+
+    private static synchronized void initializeTimer() {
+        if (timer == null) {
+            timer = new Timer("AWT-WaitDispatchSupport-Timer", true);
+        }
+    }
+
+    /**
+     * Creates a {@code WaitDispatchSupport} instance to
+     * serve the given event dispatch thread.
+     *
+     * @param dispatchThread An event dispatch thread that
+     *        should not stop dispatching events while waiting
+     *
+     * @since 1.7
+     */
+    public WaitDispatchSupport(EventDispatchThread dispatchThread) {
+        this(dispatchThread, null);
+    }
+
+    /**
+     * Creates a {@code WaitDispatchSupport} instance to
+     * serve the given event dispatch thread.
+     *
+     * @param dispatchThread An event dispatch thread that
+     *        should not stop dispatching events while waiting
+     * @param extCondition A conditional object used to determine
+     *        if the loop should be terminated
+     *
+     * @since 1.7
+     */
+    public WaitDispatchSupport(EventDispatchThread dispatchThread,
+                               Conditional extCond)
+    {
+        if (dispatchThread == null) {
+            throw new IllegalArgumentException("The dispatchThread can not be null");
+        }
+
+        this.dispatchThread = dispatchThread;
+        this.extCondition = extCond;
+        this.condition = new Conditional() {
+            @Override
+            public boolean evaluate() {
+                if (log.isLoggable(PlatformLogger.FINEST)) {
+                    log.finest("evaluate(): blockingEDT=" + keepBlockingEDT.get() +
+                               ", blockingCT=" + keepBlockingCT.get());
+                }
+                boolean extEvaluate =
+                    (extCondition != null) ? extCondition.evaluate() : true;
+                if (!keepBlockingEDT.get() || !extEvaluate) {
+                    if (timerTask != null) {
+                        timerTask.cancel();
+                        timerTask = null;
+                    }
+                    return false;
+                }
+                return true;
+            }
+        };
+    }
+
+    /**
+     * Creates a {@code WaitDispatchSupport} instance to
+     * serve the given event dispatch thread.
+     * <p>
+     * The {@link EventFilter} is set on the {@code dispatchThread}
+     * while waiting. The filter is removed on completion of the
+     * waiting process.
+     * <p>
+     *
+     *
+     * @param dispatchThread An event dispatch thread that
+     *        should not stop dispatching events while waiting
+     * @param filter {@code EventFilter} to be set
+     * @param interval A time interval to wait for. Note that
+     *        when the waiting process takes place on EDT
+     *        there is no guarantee to stop it in the given time
+     *
+     * @since 1.7
+     */
+    public WaitDispatchSupport(EventDispatchThread dispatchThread,
+                               Conditional extCondition,
+                               EventFilter filter, long interval)
+    {
+        this(dispatchThread, extCondition);
+        this.filter = filter;
+        if (interval < 0) {
+            throw new IllegalArgumentException("The interval value must be >= 0");
+        }
+        this.interval = interval;
+        if (interval != 0) {
+            initializeTimer();
+        }
+    }
+
+    /**
+     * @inheritDoc
+     */
+    @Override
+    public boolean enter() {
+        log.fine("enter(): blockingEDT=" + keepBlockingEDT.get() +
+                 ", blockingCT=" + keepBlockingCT.get());
+
+        if (!keepBlockingEDT.compareAndSet(false, true)) {
+            log.fine("The secondary loop is already running, aborting");
+            return false;
+        }
+
+        final Runnable run = new Runnable() {
+            public void run() {
+                log.fine("Starting a new event pump");
+                if (filter == null) {
+                    dispatchThread.pumpEvents(condition);
+                } else {
+                    dispatchThread.pumpEventsForFilter(condition, filter);
+                }
+            }
+        };
+
+        // We have two mechanisms for blocking: if we're on the
+        // dispatch thread, start a new event pump; if we're
+        // on any other thread, call wait() on the treelock
+
+        Thread currentThread = Thread.currentThread();
+        if (currentThread == dispatchThread) {
+            log.finest("On dispatch thread: " + dispatchThread);
+            if (interval != 0) {
+                log.finest("scheduling the timer for " + interval + " ms");
+                timer.schedule(timerTask = new TimerTask() {
+                    @Override
+                    public void run() {
+                        if (keepBlockingEDT.compareAndSet(true, false)) {
+                            wakeupEDT();
+                        }
+                    }
+                }, interval);
+            }
+            // Dispose SequencedEvent we are dispatching on the the current
+            // AppContext, to prevent us from hang - see 4531693 for details
+            SequencedEvent currentSE = KeyboardFocusManager.
+                getCurrentKeyboardFocusManager().getCurrentSequencedEvent();
+            if (currentSE != null) {
+                log.fine("Dispose current SequencedEvent: " + currentSE);
+                currentSE.dispose();
+            }
+            // In case the exit() method is called before starting
+            // new event pump it will post the waking event to EDT.
+            // The event will be handled after the the new event pump
+            // starts. Thus, the enter() method will not hang.
+            //
+            // Event pump should be privileged. See 6300270.
+            AccessController.doPrivileged(new PrivilegedAction() {
+                public Object run() {
+                    run.run();
+                    return null;
+                }
+            });
+        } else {
+            log.finest("On non-dispatch thread: " + currentThread);
+            synchronized (getTreeLock()) {
+                if (filter != null) {
+                    dispatchThread.addEventFilter(filter);
+                }
+                try {
+                    EventQueue eq = dispatchThread.getEventQueue();
+                    eq.postEvent(new PeerEvent(this, run, PeerEvent.PRIORITY_EVENT));
+                    keepBlockingCT.set(true);
+                    if (interval > 0) {
+                        long currTime = System.currentTimeMillis();
+                        while (keepBlockingCT.get() &&
+                               ((extCondition != null) ? extCondition.evaluate() : true) &&
+                               (currTime + interval > System.currentTimeMillis()))
+                        {
+                            getTreeLock().wait(interval);
+                        }
+                    } else {
+                        while (keepBlockingCT.get() &&
+                               ((extCondition != null) ? extCondition.evaluate() : true))
+                        {
+                            getTreeLock().wait();
+                        }
+                    }
+                    log.fine("waitDone " + keepBlockingEDT.get() + " " + keepBlockingCT.get());
+                } catch (InterruptedException e) {
+                    log.fine("Exception caught while waiting: " + e);
+                } finally {
+                    if (filter != null) {
+                        dispatchThread.removeEventFilter(filter);
+                    }
+                }
+                // If the waiting process has been stopped because of the
+                // time interval passed or an exception occurred, the state
+                // should be changed
+                keepBlockingEDT.set(false);
+                keepBlockingCT.set(false);
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * @inheritDoc
+     */
+    public boolean exit() {
+        log.fine("exit(): blockingEDT=" + keepBlockingEDT.get() +
+                 ", blockingCT=" + keepBlockingCT.get());
+        if (keepBlockingEDT.compareAndSet(true, false)) {
+            wakeupEDT();
+            return true;
+        }
+        return false;
+    }
+
+    private final static Object getTreeLock() {
+        return Component.LOCK;
+    }
+
+    private final Runnable wakingRunnable = new Runnable() {
+        public void run() {
+            log.fine("Wake up EDT");
+            synchronized (getTreeLock()) {
+                keepBlockingCT.set(false);
+                getTreeLock().notifyAll();
+            }
+            log.fine("Wake up EDT done");
+        }
+    };
+
+    private void wakeupEDT() {
+        log.finest("wakeupEDT(): EDT == " + dispatchThread);
+        EventQueue eq = dispatchThread.getEventQueue();
+        eq.postEvent(new PeerEvent(this, wakingRunnable, PeerEvent.PRIORITY_EVENT));
+    }
+}
--- a/src/share/classes/java/lang/Character.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/lang/Character.java	Sat Sep 25 12:00:05 2010 -0700
@@ -595,7 +595,6 @@
         /**
          * Constructs a new <code>Subset</code> instance.
          *
-         * @exception NullPointerException if name is <code>null</code>
          * @param  name  The name of this subset
          * @exception NullPointerException if name is <code>null</code>
          */
--- a/src/share/classes/java/lang/CharacterName.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/lang/CharacterName.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,12 +1,12 @@
 /*
- * Copyright 2010 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
  * 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.  Sun designates this
+ * published by the Free Software Foundation.  Oracle designates this
  * particular file as subject to the "Classpath" exception as provided
- * by Sun in the LICENSE file that accompanied this code.
+ * 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
@@ -18,9 +18,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
  */
 
 package java.lang;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/text/CalendarBuilder.java	Sat Sep 25 12:00:05 2010 -0700
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.text;
+
+import java.util.Calendar;
+import static java.util.GregorianCalendar.*;
+
+/**
+ * {@code CalendarBuilder} keeps field-value pairs for setting
+ * the calendar fields of the given {@code Calendar}. It has the
+ * {@link Calendar#FIELD_COUNT FIELD_COUNT}-th field for the week year
+ * support. Also {@code ISO_DAY_OF_WEEK} is used to specify
+ * {@code DAY_OF_WEEK} in the ISO day of week numbering.
+ *
+ * <p>{@code CalendarBuilder} retains the semantic of the pseudo
+ * timestamp for fields. {@code CalendarBuilder} uses a single
+ * int array combining fields[] and stamp[] of {@code Calendar}.
+ *
+ * @author Masayoshi Okutsu
+ */
+class CalendarBuilder {
+    /*
+     * Pseudo time stamp constants used in java.util.Calendar
+     */
+    private static final int UNSET = 0;
+    private static final int COMPUTED = 1;
+    private static final int MINIMUM_USER_STAMP = 2;
+
+    private static final int MAX_FIELD = FIELD_COUNT + 1;
+
+    public static final int WEEK_YEAR = FIELD_COUNT;
+    public static final int ISO_DAY_OF_WEEK = 1000; // pseudo field index
+
+    // stamp[] (lower half) and field[] (upper half) combined
+    private final int[] field;
+    private int nextStamp;
+    private int maxFieldIndex;
+
+    CalendarBuilder() {
+        field = new int[MAX_FIELD * 2];
+        nextStamp = MINIMUM_USER_STAMP;
+        maxFieldIndex = -1;
+    }
+
+    CalendarBuilder set(int index, int value) {
+        if (index == ISO_DAY_OF_WEEK) {
+            index = DAY_OF_WEEK;
+            value = toCalendarDayOfWeek(value);
+        }
+        field[index] = nextStamp++;
+        field[MAX_FIELD + index] = value;
+        if (index > maxFieldIndex && index < FIELD_COUNT) {
+            maxFieldIndex = index;
+        }
+        return this;
+    }
+
+    CalendarBuilder addYear(int value) {
+        field[MAX_FIELD + YEAR] += value;
+        field[MAX_FIELD + WEEK_YEAR] += value;
+        return this;
+    }
+
+    boolean isSet(int index) {
+        if (index == ISO_DAY_OF_WEEK) {
+            index = DAY_OF_WEEK;
+        }
+        return field[index] > UNSET;
+    }
+
+    Calendar establish(Calendar cal) {
+        boolean weekDate = isSet(WEEK_YEAR)
+                            && field[WEEK_YEAR] > field[YEAR];
+        if (weekDate && !cal.isWeekDateSupported()) {
+            // Use YEAR instead
+            if (!isSet(YEAR)) {
+                set(YEAR, field[MAX_FIELD + WEEK_YEAR]);
+            }
+            weekDate = false;
+        }
+
+        cal.clear();
+        // Set the fields from the min stamp to the max stamp so that
+        // the field resolution works in the Calendar.
+        for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {
+            for (int index = 0; index <= maxFieldIndex; index++) {
+                if (field[index] == stamp) {
+                    cal.set(index, field[MAX_FIELD + index]);
+                    break;
+                }
+            }
+        }
+
+        if (weekDate) {
+            int weekOfYear = isSet(WEEK_OF_YEAR) ? field[MAX_FIELD + WEEK_OF_YEAR] : 1;
+            int dayOfWeek = isSet(DAY_OF_WEEK) ?
+                                field[MAX_FIELD + DAY_OF_WEEK] : cal.getFirstDayOfWeek();
+            if (!isValidDayOfWeek(dayOfWeek) && cal.isLenient()) {
+                if (dayOfWeek >= 8) {
+                    dayOfWeek--;
+                    weekOfYear += dayOfWeek / 7;
+                    dayOfWeek = (dayOfWeek % 7) + 1;
+                } else {
+                    while (dayOfWeek <= 0) {
+                        dayOfWeek += 7;
+                        weekOfYear--;
+                    }
+                }
+                dayOfWeek = toCalendarDayOfWeek(dayOfWeek);
+            }
+            cal.setWeekDate(field[MAX_FIELD + WEEK_YEAR], weekOfYear, dayOfWeek);
+        }
+        return cal;
+    }
+
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+        sb.append("CalendarBuilder:[");
+        for (int i = 0; i < field.length; i++) {
+            if (isSet(i)) {
+                sb.append(i).append('=').append(field[MAX_FIELD + i]).append(',');
+            }
+        }
+        int lastIndex = sb.length() - 1;
+        if (sb.charAt(lastIndex) == ',') {
+            sb.setLength(lastIndex);
+        }
+        sb.append(']');
+        return sb.toString();
+    }
+
+    static int toISODayOfWeek(int calendarDayOfWeek) {
+        return calendarDayOfWeek == SUNDAY ? 7 : calendarDayOfWeek - 1;
+    }
+
+    static int toCalendarDayOfWeek(int isoDayOfWeek) {
+        if (!isValidDayOfWeek(isoDayOfWeek)) {
+            // adjust later for lenient mode
+            return isoDayOfWeek;
+        }
+        return isoDayOfWeek == 7 ? SUNDAY : isoDayOfWeek + 1;
+    }
+
+    static boolean isValidDayOfWeek(int dayOfWeek) {
+        return dayOfWeek > 0 && dayOfWeek <= 7;
+    }
+}
--- a/src/share/classes/java/text/DateFormat.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/text/DateFormat.java	Sat Sep 25 12:00:05 2010 -0700
@@ -443,7 +443,7 @@
      */
     public final static DateFormat getTimeInstance()
     {
-        return get(DEFAULT, 0, 1, Locale.getDefault());
+        return get(DEFAULT, 0, 1, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -455,7 +455,7 @@
      */
     public final static DateFormat getTimeInstance(int style)
     {
-        return get(style, 0, 1, Locale.getDefault());
+        return get(style, 0, 1, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -479,7 +479,7 @@
      */
     public final static DateFormat getDateInstance()
     {
-        return get(0, DEFAULT, 2, Locale.getDefault());
+        return get(0, DEFAULT, 2, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -491,7 +491,7 @@
      */
     public final static DateFormat getDateInstance(int style)
     {
-        return get(0, style, 2, Locale.getDefault());
+        return get(0, style, 2, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -515,7 +515,7 @@
      */
     public final static DateFormat getDateTimeInstance()
     {
-        return get(DEFAULT, DEFAULT, 3, Locale.getDefault());
+        return get(DEFAULT, DEFAULT, 3, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -530,7 +530,7 @@
     public final static DateFormat getDateTimeInstance(int dateStyle,
                                                        int timeStyle)
     {
-        return get(timeStyle, dateStyle, 3, Locale.getDefault());
+        return get(timeStyle, dateStyle, 3, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
--- a/src/share/classes/java/text/DateFormatSymbols.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/text/DateFormatSymbols.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -118,7 +118,7 @@
      */
     public DateFormatSymbols()
     {
-        initializeData(Locale.getDefault());
+        initializeData(Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -226,7 +226,30 @@
      * Unlocalized date-time pattern characters. For example: 'y', 'd', etc.
      * All locales use the same these unlocalized pattern characters.
      */
-    static final String  patternChars = "GyMdkHmsSEDFwWahKzZ";
+    static final String  patternChars = "GyMdkHmsSEDFwWahKzZYuX";
+
+    static final int PATTERN_ERA                  =  0; // G
+    static final int PATTERN_YEAR                 =  1; // y
+    static final int PATTERN_MONTH                =  2; // M
+    static final int PATTERN_DAY_OF_MONTH         =  3; // d
+    static final int PATTERN_HOUR_OF_DAY1         =  4; // k
+    static final int PATTERN_HOUR_OF_DAY0         =  5; // H
+    static final int PATTERN_MINUTE               =  6; // m
+    static final int PATTERN_SECOND               =  7; // s
+    static final int PATTERN_MILLISECOND          =  8; // S
+    static final int PATTERN_DAY_OF_WEEK          =  9; // E
+    static final int PATTERN_DAY_OF_YEAR          = 10; // D
+    static final int PATTERN_DAY_OF_WEEK_IN_MONTH = 11; // F
+    static final int PATTERN_WEEK_OF_YEAR         = 12; // w
+    static final int PATTERN_WEEK_OF_MONTH        = 13; // W
+    static final int PATTERN_AM_PM                = 14; // a
+    static final int PATTERN_HOUR1                = 15; // h
+    static final int PATTERN_HOUR0                = 16; // K
+    static final int PATTERN_ZONE_NAME            = 17; // z
+    static final int PATTERN_ZONE_VALUE           = 18; // Z
+    static final int PATTERN_WEEK_YEAR            = 19; // Y
+    static final int PATTERN_ISO_DAY_OF_WEEK      = 20; // u
+    static final int PATTERN_ISO_ZONE             = 21; // X
 
     /**
      * Localized date-time pattern characters. For example, a locale may
@@ -282,7 +305,7 @@
      * @since 1.6
      */
     public static final DateFormatSymbols getInstance() {
-        return getInstance(Locale.getDefault());
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -505,7 +528,7 @@
      * @return the localized date-time pattern characters.
      */
     public String getLocalPatternChars() {
-        return new String(localPatternChars);
+        return localPatternChars;
     }
 
     /**
@@ -514,7 +537,8 @@
      * pattern characters.
      */
     public void setLocalPatternChars(String newLocalPatternChars) {
-        localPatternChars = new String(newLocalPatternChars);
+        // Call toString() to throw an NPE in case the argument is null
+        localPatternChars = newLocalPatternChars.toString();
     }
 
     /**
@@ -699,7 +723,7 @@
         } else {
             dst.zoneStrings = null;
         }
-        dst.localPatternChars = new String (src.localPatternChars);
+        dst.localPatternChars = src.localPatternChars;
     }
 
     /**
--- a/src/share/classes/java/text/DecimalFormat.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/text/DecimalFormat.java	Sat Sep 25 12:00:05 2010 -0700
@@ -392,7 +392,7 @@
      * @see java.text.NumberFormat#getPercentInstance
      */
     public DecimalFormat() {
-        Locale def = Locale.getDefault();
+        Locale def = Locale.getDefault(Locale.Category.FORMAT);
         // try to get the pattern from the cache
         String pattern = (String) cachedLocaleData.get(def);
         if (pattern == null) {  /* cache miss */
@@ -430,7 +430,7 @@
      */
     public DecimalFormat(String pattern) {
         // Always applyPattern after the symbols are set
-        this.symbols = new DecimalFormatSymbols(Locale.getDefault());
+        this.symbols = new DecimalFormatSymbols(Locale.getDefault(Locale.Category.FORMAT));
         applyPattern(pattern, false);
     }
 
--- a/src/share/classes/java/text/DecimalFormatSymbols.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/text/DecimalFormatSymbols.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,10 +43,10 @@
 import java.io.Serializable;
 import java.text.spi.DecimalFormatSymbolsProvider;
 import java.util.Currency;
-import java.util.Hashtable;
 import java.util.Locale;
 import java.util.ResourceBundle;
-import java.util.spi.LocaleServiceProvider;
+import java.util.concurrent.ConcurrentHashMap;
+
 import sun.util.LocaleServiceProviderPool;
 import sun.util.resources.LocaleData;
 
@@ -76,7 +76,7 @@
      * {@link #getInstance(Locale) getInstance} method.
      */
     public DecimalFormatSymbols() {
-        initialize( Locale.getDefault() );
+        initialize( Locale.getDefault(Locale.Category.FORMAT) );
     }
 
     /**
@@ -125,7 +125,7 @@
      * @since 1.6
      */
     public static final DecimalFormatSymbols getInstance() {
-        return getInstance(Locale.getDefault());
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -527,10 +527,17 @@
 
         // get resource bundle data - try the cache first
         boolean needCacheUpdate = false;
-        Object[] data = (Object[]) cachedLocaleData.get(locale);
+        Object[] data = cachedLocaleData.get(locale);
         if (data == null) {  /* cache miss */
+            // When numbering system is thai (Locale's extension contains u-nu-thai),
+            // we read the data from th_TH_TH.
+            Locale lookupLocale = locale;
+            String numberType = locale.getUnicodeLocaleType("nu");
+            if (numberType != null && numberType.equals("thai")) {
+                lookupLocale = new Locale("th", "TH", "TH");
+            }
             data = new Object[3];
-            ResourceBundle rb = LocaleData.getNumberFormatData(locale);
+            ResourceBundle rb = LocaleData.getNumberFormatData(lookupLocale);
             data[0] = rb.getStringArray("NumberElements");
             needCacheUpdate = true;
         }
@@ -586,7 +593,7 @@
         monetarySeparator = decimalSeparator;
 
         if (needCacheUpdate) {
-            cachedLocaleData.put(locale, data);
+            cachedLocaleData.putIfAbsent(locale, data);
         }
     }
 
@@ -806,7 +813,7 @@
      * cache to hold the NumberElements and the Currency
      * of a Locale.
      */
-    private static final Hashtable cachedLocaleData = new Hashtable(3);
+    private static final ConcurrentHashMap<Locale, Object[]> cachedLocaleData = new ConcurrentHashMap<Locale, Object[]>(3);
 
     /**
      * Obtains a DecimalFormatSymbols instance from a DecimalFormatSymbolsProvider
--- a/src/share/classes/java/text/MessageFormat.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/text/MessageFormat.java	Sat Sep 25 12:00:05 2010 -0700
@@ -363,7 +363,7 @@
      * @exception IllegalArgumentException if the pattern is invalid
      */
     public MessageFormat(String pattern) {
-        this.locale = Locale.getDefault();
+        this.locale = Locale.getDefault(Locale.Category.FORMAT);
         applyPattern(pattern);
     }
 
--- a/src/share/classes/java/text/NumberFormat.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/text/NumberFormat.java	Sat Sep 25 12:00:05 2010 -0700
@@ -381,7 +381,7 @@
      * {@link #getNumberInstance() getNumberInstance()}.
      */
     public final static NumberFormat getInstance() {
-        return getInstance(Locale.getDefault(), NUMBERSTYLE);
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE);
     }
 
     /**
@@ -397,7 +397,7 @@
      * Returns a general-purpose number format for the current default locale.
      */
     public final static NumberFormat getNumberInstance() {
-        return getInstance(Locale.getDefault(), NUMBERSTYLE);
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE);
     }
 
     /**
@@ -420,7 +420,7 @@
      * @since 1.4
      */
     public final static NumberFormat getIntegerInstance() {
-        return getInstance(Locale.getDefault(), INTEGERSTYLE);
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT), INTEGERSTYLE);
     }
 
     /**
@@ -443,7 +443,7 @@
      * Returns a currency format for the current default locale.
      */
     public final static NumberFormat getCurrencyInstance() {
-        return getInstance(Locale.getDefault(), CURRENCYSTYLE);
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT), CURRENCYSTYLE);
     }
 
     /**
@@ -457,7 +457,7 @@
      * Returns a percentage format for the current default locale.
      */
     public final static NumberFormat getPercentInstance() {
-        return getInstance(Locale.getDefault(), PERCENTSTYLE);
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT), PERCENTSTYLE);
     }
 
     /**
@@ -471,7 +471,7 @@
      * Returns a scientific format for the current default locale.
      */
     /*public*/ final static NumberFormat getScientificInstance() {
-        return getInstance(Locale.getDefault(), SCIENTIFICSTYLE);
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT), SCIENTIFICSTYLE);
     }
 
     /**
--- a/src/share/classes/java/text/SimpleDateFormat.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/text/SimpleDateFormat.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -55,6 +55,8 @@
 import sun.util.calendar.ZoneInfoFile;
 import sun.util.resources.LocaleData;
 
+import static java.text.DateFormatSymbols.*;
+
 /**
  * <code>SimpleDateFormat</code> is a concrete class for formatting and
  * parsing dates in a locale-sensitive manner. It allows for formatting
@@ -108,40 +110,50 @@
  *         <td><a href="#year">Year</a>
  *         <td><code>1996</code>; <code>96</code>
  *     <tr>
+ *         <td><code>Y</code>
+ *         <td>Week year
+ *         <td><a href="#year">Year</a>
+ *         <td><code>2009</code>; <code>09</code>
+ *     <tr bgcolor="#eeeeff">
  *         <td><code>M</code>
  *         <td>Month in year
  *         <td><a href="#month">Month</a>
  *         <td><code>July</code>; <code>Jul</code>; <code>07</code>
- *     <tr bgcolor="#eeeeff">
+ *     <tr>
  *         <td><code>w</code>
  *         <td>Week in year
  *         <td><a href="#number">Number</a>
  *         <td><code>27</code>
- *     <tr>
+ *     <tr bgcolor="#eeeeff">
  *         <td><code>W</code>
  *         <td>Week in month
  *         <td><a href="#number">Number</a>
  *         <td><code>2</code>
- *     <tr bgcolor="#eeeeff">
+ *     <tr>
  *         <td><code>D</code>
  *         <td>Day in year
  *         <td><a href="#number">Number</a>
  *         <td><code>189</code>
- *     <tr>
+ *     <tr bgcolor="#eeeeff">
  *         <td><code>d</code>
  *         <td>Day in month
  *         <td><a href="#number">Number</a>
  *         <td><code>10</code>
- *     <tr bgcolor="#eeeeff">
+ *     <tr>
  *         <td><code>F</code>
  *         <td>Day of week in month
  *         <td><a href="#number">Number</a>
  *         <td><code>2</code>
- *     <tr>
+ *     <tr bgcolor="#eeeeff">
  *         <td><code>E</code>
- *         <td>Day in week
+ *         <td>Day name in week
  *         <td><a href="#text">Text</a>
  *         <td><code>Tuesday</code>; <code>Tue</code>
+ *     <tr>
+ *         <td><code>u</code>
+ *         <td>Day number of week (1 = Monday, ..., 7 = Sunday)
+ *         <td><a href="#number">Number</a>
+ *         <td><code>1</code>
  *     <tr bgcolor="#eeeeff">
  *         <td><code>a</code>
  *         <td>Am/pm marker
@@ -192,6 +204,11 @@
  *         <td>Time zone
  *         <td><a href="#rfc822timezone">RFC 822 time zone</a>
  *         <td><code>-0800</code>
+ *     <tr bgcolor="#eeeeff">
+ *         <td><code>X</code>
+ *         <td>Time zone
+ *         <td><a href="#iso8601timezone">ISO 8601 time zone</a>
+ *         <td><code>-08</code>; <code>-0800</code>;  <code>-08:00</code>
  * </table>
  * </blockquote>
  * Pattern letters are usually repeated, as their number determines the
@@ -202,12 +219,12 @@
  *     the full form is used; otherwise a short or abbreviated form
  *     is used if available.
  *     For parsing, both forms are accepted, independent of the number
- *     of pattern letters.
+ *     of pattern letters.<br><br></li>
  * <li><strong><a name="number">Number:</a></strong>
  *     For formatting, the number of pattern letters is the minimum
  *     number of digits, and shorter numbers are zero-padded to this amount.
  *     For parsing, the number of pattern letters is ignored unless
- *     it's needed to separate two adjacent fields.
+ *     it's needed to separate two adjacent fields.<br><br></li>
  * <li><strong><a name="year">Year:</a></strong>
  *     If the formatter's {@link #getCalendar() Calendar} is the Gregorian
  *     calendar, the following rules are applied.<br>
@@ -239,11 +256,20 @@
  *     letters is 4 or more, a calendar specific {@linkplain
  *     Calendar#LONG long form} is used. Otherwise, a calendar
  *     specific {@linkplain Calendar#SHORT short or abbreviated form}
- *     is used.
+ *     is used.<br>
+ *     <br>
+ *     If week year {@code 'Y'} is specified and the {@linkplain
+ *     #getCalendar() calendar} doesn't support any <a
+ *     href="../util/GregorianCalendar.html#week_year"> week
+ *     years</a>, the calendar year ({@code 'y'}) is used instead. The
+ *     support of week years can be tested with a call to {@link
+ *     DateFormat#getCalendar() getCalendar()}.{@link
+ *     java.util.Calendar#isWeekDateSupported()
+ *     isWeekDateSupported()}.<br><br></li>
  * <li><strong><a name="month">Month:</a></strong>
  *     If the number of pattern letters is 3 or more, the month is
  *     interpreted as <a href="#text">text</a>; otherwise,
- *     it is interpreted as a <a href="#number">number</a>.
+ *     it is interpreted as a <a href="#number">number</a>.<br><br></li>
  * <li><strong><a name="timezone">General time zone:</a></strong>
  *     Time zones are interpreted as <a href="#text">text</a> if they have
  *     names. For time zones representing a GMT offset value, the
@@ -264,9 +290,10 @@
  *     00 and 59. The format is locale independent and digits must be taken
  *     from the Basic Latin block of the Unicode standard.
  *     <p>For parsing, <a href="#rfc822timezone">RFC 822 time zones</a> are also
- *     accepted.
+ *     accepted.<br><br></li>
  * <li><strong><a name="rfc822timezone">RFC 822 time zone:</a></strong>
  *     For formatting, the RFC 822 4-digit time zone format is used:
+ *
  *     <pre>
  *     <i>RFC822TimeZone:</i>
  *             <i>Sign</i> <i>TwoDigitHours</i> <i>Minutes</i>
@@ -274,8 +301,41 @@
  *             <i>Digit Digit</i></pre>
  *     <i>TwoDigitHours</i> must be between 00 and 23. Other definitions
  *     are as for <a href="#timezone">general time zones</a>.
+ *
  *     <p>For parsing, <a href="#timezone">general time zones</a> are also
  *     accepted.
+ * <li><strong><a name="iso8601timezone">ISO 8601 Time zone:</a></strong>
+ *     The number of pattern letters designates the format for both formatting
+ *     and parsing as follows:
+ *     <pre>
+ *     <i>ISO8601TimeZone:</i>
+ *             <i>OneLetterISO8601TimeZone</i>
+ *             <i>TwoLetterISO8601TimeZone</i>
+ *             <i>ThreeLetterISO8601TimeZone</i>
+ *     <i>OneLetterISO8601TimeZone:</i>
+ *             <i>Sign</i> <i>TwoDigitHours</i>
+ *             {@code Z}
+ *     <i>TwoLetterISO8601TimeZone:</i>
+ *             <i>Sign</i> <i>TwoDigitHours</i> <i>Minutes</i>
+ *             {@code Z}
+ *     <i>ThreeLetterISO8601TimeZone:</i>
+ *             <i>Sign</i> <i>TwoDigitHours</i> {@code :} <i>Minutes</i>
+ *             {@code Z}</pre>
+ *     Other definitions are as for <a href="#timezone">general time zones</a> or
+ *     <a href="#rfc822timezone">RFC 822 time zones</a>.
+ *
+ *     <p>For formatting, if the offset value from GMT is 0, {@code "Z"} is
+ *     produced. If the number of pattern letters is 1, any fraction of an hour
+ *     is ignored. For example, if the pattern is {@code "X"} and the time zone is
+ *     {@code "GMT+05:30"}, {@code "+05"} is produced.
+ *
+ *     <p>For parsing, {@code "Z"} is parsed as the UTC time zone designator.
+ *     <a href="#timezone">General time zones</a> are <em>not</em> accepted.
+ *
+ *     <p>If the number of pattern letters is 4 or more, {@link
+ *     IllegalArgumentException} is thrown when constructing a {@code
+ *     SimpleDateFormat} or {@linkplain #applyPattern(String) applying a
+ *     pattern}.
  * </ul>
  * <code>SimpleDateFormat</code> also supports <em>localized date and time
  * pattern</em> strings. In these strings, the pattern letters described above
@@ -321,6 +381,12 @@
  *     <tr>
  *         <td><code>"yyyy-MM-dd'T'HH:mm:ss.SSSZ"</code>
  *         <td><code>2001-07-04T12:08:56.235-0700</code>
+ *     <tr bgcolor="#eeeeff">
+ *         <td><code>"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"</code>
+ *         <td><code>2001-07-04T12:08:56.235-07:00</code>
+ *     <tr>
+ *         <td><code>"YYYY-'W'ww-u"</code>
+ *         <td><code>2001-W27-3</code>
  * </table>
  * </blockquote>
  *
@@ -474,7 +540,7 @@
      * class.
      */
     public SimpleDateFormat() {
-        this(SHORT, SHORT, Locale.getDefault());
+        this(SHORT, SHORT, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -490,7 +556,7 @@
      */
     public SimpleDateFormat(String pattern)
     {
-        this(pattern, Locale.getDefault());
+        this(pattern, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -535,7 +601,7 @@
 
         this.pattern = pattern;
         this.formatData = (DateFormatSymbols) formatSymbols.clone();
-        this.locale = Locale.getDefault();
+        this.locale = Locale.getDefault(Locale.Category.FORMAT);
         initializeCalendar(this.locale);
         initialize(this.locale);
         useDateFormatSymbols = true;
@@ -815,6 +881,9 @@
      * Encodes the given tag and length and puts encoded char(s) into buffer.
      */
     private static final void encode(int tag, int length, StringBuilder buffer) {
+        if (tag == PATTERN_ISO_ZONE && length >= 4) {
+            throw new IllegalArgumentException("invalid ISO 8601 format: length=" + length);
+        }
         if (length < 255) {
             buffer.append((char)(tag << 8 | length));
         } else {
@@ -877,7 +946,7 @@
      * @param pos the formatting position. On input: an alignment field,
      * if desired. On output: the offsets of the alignment field.
      * @return the formatted date-time string.
-     * @exception NullPointerException if the given date is null
+     * @exception NullPointerException if the given {@code date} is {@code null}.
      */
     public StringBuffer format(Date date, StringBuffer toAppendTo,
                                FieldPosition pos)
@@ -968,6 +1037,10 @@
         Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK_IN_MONTH,
         Calendar.WEEK_OF_YEAR, Calendar.WEEK_OF_MONTH,
         Calendar.AM_PM, Calendar.HOUR, Calendar.HOUR, Calendar.ZONE_OFFSET,
+        Calendar.ZONE_OFFSET,
+        // Pseudo Calendar fields
+        CalendarBuilder.WEEK_YEAR,
+        CalendarBuilder.ISO_DAY_OF_WEEK,
         Calendar.ZONE_OFFSET
     };
 
@@ -982,6 +1055,8 @@
         DateFormat.WEEK_OF_MONTH_FIELD, DateFormat.AM_PM_FIELD,
         DateFormat.HOUR1_FIELD, DateFormat.HOUR0_FIELD,
         DateFormat.TIMEZONE_FIELD, DateFormat.TIMEZONE_FIELD,
+        DateFormat.YEAR_FIELD, DateFormat.DAY_OF_WEEK_FIELD,
+        DateFormat.TIMEZONE_FIELD
     };
 
     // Maps from DecimalFormatSymbols index to Field constant
@@ -993,6 +1068,8 @@
         Field.WEEK_OF_YEAR, Field.WEEK_OF_MONTH,
         Field.AM_PM, Field.HOUR1, Field.HOUR0, Field.TIME_ZONE,
         Field.TIME_ZONE,
+        Field.YEAR, Field.DAY_OF_WEEK,
+        Field.TIME_ZONE
     };
 
     /**
@@ -1007,9 +1084,24 @@
         int     beginOffset = buffer.length();
 
         int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
-        int value = calendar.get(field);
+        int value;
+        if (field == CalendarBuilder.WEEK_YEAR) {
+            if (calendar.isWeekDateSupported()) {
+                value = calendar.getWeekYear();
+            } else {
+                // use calendar year 'y' instead
+                patternCharIndex = PATTERN_YEAR;
+                field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
+                value = calendar.get(field);
+            }
+        } else if (field == CalendarBuilder.ISO_DAY_OF_WEEK) {
+            value = CalendarBuilder.toISODayOfWeek(calendar.get(Calendar.DAY_OF_WEEK));
+        } else {
+            value = calendar.get(field);
+        }
+
         int style = (count >= 4) ? Calendar.LONG : Calendar.SHORT;
-        if (!useDateFormatSymbols) {
+        if (!useDateFormatSymbols && field != CalendarBuilder.ISO_DAY_OF_WEEK) {
             current = calendar.getDisplayName(field, style, locale);
         }
 
@@ -1018,7 +1110,7 @@
         // zeroPaddingNumber() must be fixed.
 
         switch (patternCharIndex) {
-        case 0: // 'G' - ERA
+        case PATTERN_ERA: // 'G'
             if (useDateFormatSymbols) {
                 String[] eras = formatData.getEras();
                 if (value < eras.length)
@@ -1028,7 +1120,8 @@
                 current = "";
             break;
 
-        case 1: // 'y' - YEAR
+        case PATTERN_WEEK_YEAR: // 'Y'
+        case PATTERN_YEAR:      // 'y'
             if (calendar instanceof GregorianCalendar) {
                 if (count != 2)
                     zeroPaddingNumber(value, count, maxIntCount, buffer);
@@ -1042,7 +1135,7 @@
             }
             break;
 
-        case 2: // 'M' - MONTH
+        case PATTERN_MONTH: // 'M'
             if (useDateFormatSymbols) {
                 String[] months;
                 if (count >= 4) {
@@ -1062,7 +1155,7 @@
             }
             break;
 
-        case 4: // 'k' - HOUR_OF_DAY: 1-based.  eg, 23:59 + 1 hour =>> 24:59
+        case PATTERN_HOUR_OF_DAY1: // 'k' 1-based.  eg, 23:59 + 1 hour =>> 24:59
             if (current == null) {
                 if (value == 0)
                     zeroPaddingNumber(calendar.getMaximum(Calendar.HOUR_OF_DAY)+1,
@@ -1072,7 +1165,7 @@
             }
             break;
 
-        case 9: // 'E' - DAY_OF_WEEK
+        case PATTERN_DAY_OF_WEEK: // 'E'
             if (useDateFormatSymbols) {
                 String[] weekdays;
                 if (count >= 4) {
@@ -1085,14 +1178,14 @@
             }
             break;
 
-        case 14:    // 'a' - AM_PM
+        case PATTERN_AM_PM:    // 'a'
             if (useDateFormatSymbols) {
                 String[] ampm = formatData.getAmPmStrings();
                 current = ampm[value];
             }
             break;
 
-        case 15: // 'h' - HOUR:1-based.  eg, 11PM + 1 hour =>> 12 AM
+        case PATTERN_HOUR1:    // 'h' 1-based.  eg, 11PM + 1 hour =>> 12 AM
             if (current == null) {
                 if (value == 0)
                     zeroPaddingNumber(calendar.getLeastMaximum(Calendar.HOUR)+1,
@@ -1102,7 +1195,7 @@
             }
             break;
 
-        case 17: // 'z' - ZONE_OFFSET
+        case PATTERN_ZONE_NAME: // 'z'
             if (current == null) {
                 if (formatData.locale == null || formatData.isZoneStringsSet) {
                     int zoneIndex =
@@ -1129,7 +1222,7 @@
             }
             break;
 
-        case 18: // 'Z' - ZONE_OFFSET ("-/+hhmm" form)
+        case PATTERN_ZONE_VALUE: // 'Z' ("-/+hhmm" form)
             value = (calendar.get(Calendar.ZONE_OFFSET) +
                      calendar.get(Calendar.DST_OFFSET)) / 60000;
 
@@ -1144,17 +1237,46 @@
             CalendarUtils.sprintf0d(buffer, num, width);
             break;
 
+        case PATTERN_ISO_ZONE:   // 'X'
+            value = calendar.get(Calendar.ZONE_OFFSET)
+                    + calendar.get(Calendar.DST_OFFSET);
+
+            if (value == 0) {
+                buffer.append('Z');
+                break;
+            }
+
+            value /=  60000;
+            if (value >= 0) {
+                buffer.append('+');
+            } else {
+                buffer.append('-');
+                value = -value;
+            }
+
+            CalendarUtils.sprintf0d(buffer, value / 60, 2);
+            if (count == 1) {
+                break;
+            }
+
+            if (count == 3) {
+                buffer.append(':');
+            }
+            CalendarUtils.sprintf0d(buffer, value % 60, 2);
+            break;
+
         default:
-            // case 3: // 'd' - DATE
-            // case 5: // 'H' - HOUR_OF_DAY:0-based.  eg, 23:59 + 1 hour =>> 00:59
-            // case 6: // 'm' - MINUTE
-            // case 7: // 's' - SECOND
-            // case 8: // 'S' - MILLISECOND
-            // case 10: // 'D' - DAY_OF_YEAR
-            // case 11: // 'F' - DAY_OF_WEEK_IN_MONTH
-            // case 12: // 'w' - WEEK_OF_YEAR
-            // case 13: // 'W' - WEEK_OF_MONTH
-            // case 16: // 'K' - HOUR: 0-based.  eg, 11PM + 1 hour =>> 0 AM
+     // case PATTERN_DAY_OF_MONTH:         // 'd'
+     // case PATTERN_HOUR_OF_DAY0:         // 'H' 0-based.  eg, 23:59 + 1 hour =>> 00:59
+     // case PATTERN_MINUTE:               // 'm'
+     // case PATTERN_SECOND:               // 's'
+     // case PATTERN_MILLISECOND:          // 'S'
+     // case PATTERN_DAY_OF_YEAR:          // 'D'
+     // case PATTERN_DAY_OF_WEEK_IN_MONTH: // 'F'
+     // case PATTERN_WEEK_OF_YEAR:         // 'w'
+     // case PATTERN_WEEK_OF_MONTH:        // 'W'
+     // case PATTERN_HOUR0:                // 'K' eg, 11PM + 1 hour =>> 0 AM
+     // case PATTERN_ISO_DAY_OF_WEEK:      // 'u' pseudo field, Monday = 1, ..., Sunday = 7
             if (current == null) {
                 zeroPaddingNumber(value, count, maxIntCount, buffer);
             }
@@ -1264,10 +1386,9 @@
         int oldStart = start;
         int textLength = text.length();
 
-        calendar.clear(); // Clears all the time fields
-
         boolean[] ambiguousYear = {false};
 
+        CalendarBuilder calb = new CalendarBuilder();
 
         for (int i = 0; i < compiledPattern.length; ) {
             int tag = compiledPattern[i] >>> 8;
@@ -1340,7 +1461,7 @@
                 }
                 start = subParse(text, start, tag, count, obeyCount,
                                  ambiguousYear, pos,
-                                 useFollowingMinusSignAsDelimiter);
+                                 useFollowingMinusSignAsDelimiter, calb);
                 if (start < 0) {
                     pos.index = oldStart;
                     return null;
@@ -1354,46 +1475,16 @@
 
         pos.index = start;
 
-        // This part is a problem:  When we call parsedDate.after, we compute the time.
-        // Take the date April 3 2004 at 2:30 am.  When this is first set up, the year
-        // will be wrong if we're parsing a 2-digit year pattern.  It will be 1904.
-        // April 3 1904 is a Sunday (unlike 2004) so it is the DST onset day.  2:30 am
-        // is therefore an "impossible" time, since the time goes from 1:59 to 3:00 am
-        // on that day.  It is therefore parsed out to fields as 3:30 am.  Then we
-        // add 100 years, and get April 3 2004 at 3:30 am.  Note that April 3 2004 is
-        // a Saturday, so it can have a 2:30 am -- and it should. [LIU]
-        /*
-        Date parsedDate = calendar.getTime();
-        if( ambiguousYear[0] && !parsedDate.after(defaultCenturyStart) ) {
-            calendar.add(Calendar.YEAR, 100);
-            parsedDate = calendar.getTime();
-        }
-        */
-        // Because of the above condition, save off the fields in case we need to readjust.
-        // The procedure we use here is not particularly efficient, but there is no other
-        // way to do this given the API restrictions present in Calendar.  We minimize
-        // inefficiency by only performing this computation when it might apply, that is,
-        // when the two-digit year is equal to the start year, and thus might fall at the
-        // front or the back of the default century.  This only works because we adjust
-        // the year correctly to start with in other cases -- see subParse().
         Date parsedDate;
         try {
-            if (ambiguousYear[0]) // If this is true then the two-digit year == the default start year
-            {
-                // We need a copy of the fields, and we need to avoid triggering a call to
-                // complete(), which will recalculate the fields.  Since we can't access
-                // the fields[] array in Calendar, we clone the entire object.  This will
-                // stop working if Calendar.clone() is ever rewritten to call complete().
-                Calendar savedCalendar = (Calendar)calendar.clone();
-                parsedDate = calendar.getTime();
-                if (parsedDate.before(defaultCenturyStart))
-                {
-                    // We can't use add here because that does a complete() first.
-                    savedCalendar.set(Calendar.YEAR, defaultCenturyStartYear + 100);
-                    parsedDate = savedCalendar.getTime();
+            parsedDate = calb.establish(calendar).getTime();
+            // If the year value is ambiguous,
+            // then the two-digit year == the default start year
+            if (ambiguousYear[0]) {
+                if (parsedDate.before(defaultCenturyStart)) {
+                    parsedDate = calb.addYear(100).establish(calendar).getTime();
                 }
             }
-            else parsedDate = calendar.getTime();
         }
         // An IllegalArgumentException will be thrown by Calendar.getTime()
         // if any fields are out of range, e.g., MONTH == 17.
@@ -1415,7 +1506,7 @@
      * @return the new start position if matching succeeded; a negative number
      * indicating matching failure, otherwise.
      */
-    private int matchString(String text, int start, int field, String[] data)
+    private int matchString(String text, int start, int field, String[] data, CalendarBuilder calb)
     {
         int i = 0;
         int count = data.length;
@@ -1441,7 +1532,7 @@
         }
         if (bestMatch >= 0)
         {
-            calendar.set(field, bestMatch);
+            calb.set(field, bestMatch);
             return start + bestMatchLength;
         }
         return -start;
@@ -1452,7 +1543,8 @@
      * String[]). This method takes a Map<String, Integer> instead of
      * String[].
      */
-    private int matchString(String text, int start, int field, Map<String,Integer> data) {
+    private int matchString(String text, int start, int field,
+                            Map<String,Integer> data, CalendarBuilder calb) {
         if (data != null) {
             String bestMatch = null;
 
@@ -1466,7 +1558,7 @@
             }
 
             if (bestMatch != null) {
-                calendar.set(field, data.get(bestMatch));
+                calb.set(field, data.get(bestMatch));
                 return start + bestMatch.length();
             }
         }
@@ -1486,11 +1578,22 @@
         return -1;
     }
 
+    private boolean matchDSTString(String text, int start, int zoneIndex, int standardIndex,
+                                   String[][] zoneStrings) {
+        int index = standardIndex + 2;
+        String zoneName  = zoneStrings[zoneIndex][index];
+        if (text.regionMatches(true, start,
+                               zoneName, 0, zoneName.length())) {
+            return true;
+        }
+        return false;
+    }
+
     /**
      * find time zone 'text' matched zoneStrings and set to internal
      * calendar.
      */
-    private int subParseZoneString(String text, int start) {
+    private int subParseZoneString(String text, int start, CalendarBuilder calb) {
         boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
         TimeZone currentTimeZone = getTimeZone();
 
@@ -1524,6 +1627,7 @@
                 }
             }
         }
+
         if (tz == null) {
             int len = zoneStrings.length;
             for (int i = 0; i < len; i++) {
@@ -1549,8 +1653,8 @@
             // determine the local time. (6645292)
             int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
             if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
-                calendar.set(Calendar.ZONE_OFFSET, tz.getRawOffset());
-                calendar.set(Calendar.DST_OFFSET, dstAmount);
+                calb.set(Calendar.ZONE_OFFSET, tz.getRawOffset())
+                    .set(Calendar.DST_OFFSET, dstAmount);
             }
             return (start + zoneNames[nameIndex].length());
         }
@@ -1577,11 +1681,15 @@
     private int subParse(String text, int start, int patternCharIndex, int count,
                          boolean obeyCount, boolean[] ambiguousYear,
                          ParsePosition origPos,
-                         boolean useFollowingMinusSignAsDelimiter) {
+                         boolean useFollowingMinusSignAsDelimiter, CalendarBuilder calb) {
         Number number = null;
         int value = 0;
         ParsePosition pos = new ParsePosition(0);
         pos.index = start;
+        if (patternCharIndex == PATTERN_WEEK_YEAR && !calendar.isWeekDateSupported()) {
+            // use calendar year 'y' instead
+            patternCharIndex = PATTERN_YEAR;
+        }
         int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
 
         // If there are any spaces here, skip over them.  If we hit the end
@@ -1602,10 +1710,11 @@
             // a number value.  We handle further, more generic cases below.  We need
             // to handle some of them here because some fields require extra processing on
             // the parsed value.
-            if (patternCharIndex == 4 /* HOUR_OF_DAY1_FIELD */ ||
-                patternCharIndex == 15 /* HOUR1_FIELD */ ||
-                (patternCharIndex == 2 /* MONTH_FIELD */ && count <= 2) ||
-                patternCharIndex == 1 /* YEAR_FIELD */) {
+            if (patternCharIndex == PATTERN_HOUR_OF_DAY1 ||
+                patternCharIndex == PATTERN_HOUR1 ||
+                (patternCharIndex == PATTERN_MONTH && count <= 2) ||
+                patternCharIndex == PATTERN_YEAR ||
+                patternCharIndex == PATTERN_WEEK_YEAR) {
                 // It would be good to unify this with the obeyCount logic below,
                 // but that's going to be difficult.
                 if (obeyCount) {
@@ -1617,7 +1726,7 @@
                     number = numberFormat.parse(text, pos);
                 }
                 if (number == null) {
-                    if (patternCharIndex != 1 || calendar instanceof GregorianCalendar) {
+                    if (patternCharIndex != PATTERN_YEAR || calendar instanceof GregorianCalendar) {
                         break parsing;
                     }
                 } else {
@@ -1638,33 +1747,34 @@
 
             int index;
             switch (patternCharIndex) {
-            case 0: // 'G' - ERA
+            case PATTERN_ERA: // 'G'
                 if (useDateFormatSymbols) {
-                    if ((index = matchString(text, start, Calendar.ERA, formatData.getEras())) > 0) {
+                    if ((index = matchString(text, start, Calendar.ERA, formatData.getEras(), calb)) > 0) {
                         return index;
                     }
                 } else {
                     Map<String, Integer> map = calendar.getDisplayNames(field,
                                                                         Calendar.ALL_STYLES,
                                                                         locale);
-                    if ((index = matchString(text, start, field, map)) > 0) {
+                    if ((index = matchString(text, start, field, map, calb)) > 0) {
                         return index;
                     }
                 }
                 break parsing;
 
-            case 1: // 'y' - YEAR
+            case PATTERN_WEEK_YEAR: // 'Y'
+            case PATTERN_YEAR:      // 'y'
                 if (!(calendar instanceof GregorianCalendar)) {
                     // calendar might have text representations for year values,
                     // such as "\u5143" in JapaneseImperialCalendar.
                     int style = (count >= 4) ? Calendar.LONG : Calendar.SHORT;
                     Map<String, Integer> map = calendar.getDisplayNames(field, style, locale);
                     if (map != null) {
-                        if ((index = matchString(text, start, field, map)) > 0) {
+                        if ((index = matchString(text, start, field, map, calb)) > 0) {
                             return index;
                         }
                     }
-                    calendar.set(field, value);
+                    calb.set(field, value);
                     return pos.index;
                 }
 
@@ -1676,8 +1786,7 @@
                 // is treated literally:  "2250", "-1", "1", "002".
                 if (count <= 2 && (pos.index - start) == 2
                     && Character.isDigit(text.charAt(start))
-                    && Character.isDigit(text.charAt(start+1)))
-                {
+                    && Character.isDigit(text.charAt(start+1))) {
                     // Assume for example that the defaultCenturyStart is 6/18/1903.
                     // This means that two-digit years will be forced into the range
                     // 6/18/1903 to 6/17/2003.  As a result, years 00, 01, and 02
@@ -1691,16 +1800,16 @@
                     value += (defaultCenturyStartYear/100)*100 +
                         (value < ambiguousTwoDigitYear ? 100 : 0);
                 }
-                calendar.set(Calendar.YEAR, value);
+                calb.set(field, value);
                 return pos.index;
 
-            case 2: // 'M' - MONTH
+            case PATTERN_MONTH: // 'M'
                 if (count <= 2) // i.e., M or MM.
                 {
                     // Don't want to parse the month if it is a string
                     // while pattern uses numeric style: M or MM.
                     // [We computed 'value' above.]
-                    calendar.set(Calendar.MONTH, value - 1);
+                    calb.set(Calendar.MONTH, value - 1);
                     return pos.index;
                 }
 
@@ -1710,50 +1819,50 @@
                     // Try count == 4 first:
                     int newStart = 0;
                     if ((newStart = matchString(text, start, Calendar.MONTH,
-                                                formatData.getMonths())) > 0) {
+                                                formatData.getMonths(), calb)) > 0) {
                         return newStart;
                     }
                     // count == 4 failed, now try count == 3
                     if ((index = matchString(text, start, Calendar.MONTH,
-                                             formatData.getShortMonths())) > 0) {
+                                             formatData.getShortMonths(), calb)) > 0) {
                         return index;
                     }
                 } else {
                     Map<String, Integer> map = calendar.getDisplayNames(field,
                                                                         Calendar.ALL_STYLES,
                                                                         locale);
-                    if ((index = matchString(text, start, field, map)) > 0) {
+                    if ((index = matchString(text, start, field, map, calb)) > 0) {
                         return index;
                     }
                 }
                 break parsing;
 
-            case 4: // 'k' - HOUR_OF_DAY: 1-based.  eg, 23:59 + 1 hour =>> 24:59
+            case PATTERN_HOUR_OF_DAY1: // 'k' 1-based.  eg, 23:59 + 1 hour =>> 24:59
                 // [We computed 'value' above.]
                 if (value == calendar.getMaximum(Calendar.HOUR_OF_DAY)+1) value = 0;
-                calendar.set(Calendar.HOUR_OF_DAY, value);
+                calb.set(Calendar.HOUR_OF_DAY, value);
                 return pos.index;
 
-            case 9:
-                { // 'E' - DAY_OF_WEEK
+            case PATTERN_DAY_OF_WEEK:  // 'E'
+                {
                     if (useDateFormatSymbols) {
                         // Want to be able to parse both short and long forms.
                         // Try count == 4 (DDDD) first:
                         int newStart = 0;
                         if ((newStart=matchString(text, start, Calendar.DAY_OF_WEEK,
-                                                  formatData.getWeekdays())) > 0) {
+                                                  formatData.getWeekdays(), calb)) > 0) {
                             return newStart;
                         }
                         // DDDD failed, now try DDD
                         if ((index = matchString(text, start, Calendar.DAY_OF_WEEK,
-                                                 formatData.getShortWeekdays())) > 0) {
+                                                 formatData.getShortWeekdays(), calb)) > 0) {
                             return index;
                         }
                     } else {
                         int[] styles = { Calendar.LONG, Calendar.SHORT };
                         for (int style : styles) {
                             Map<String,Integer> map = calendar.getDisplayNames(field, style, locale);
-                            if ((index = matchString(text, start, field, map)) > 0) {
+                            if ((index = matchString(text, start, field, map, calb)) > 0) {
                                 return index;
                             }
                         }
@@ -1761,27 +1870,28 @@
                 }
                 break parsing;
 
-            case 14:    // 'a' - AM_PM
+            case PATTERN_AM_PM:    // 'a'
                 if (useDateFormatSymbols) {
-                    if ((index = matchString(text, start, Calendar.AM_PM, formatData.getAmPmStrings())) > 0) {
+                    if ((index = matchString(text, start, Calendar.AM_PM,
+                                             formatData.getAmPmStrings(), calb)) > 0) {
                         return index;
                     }
                 } else {
                     Map<String,Integer> map = calendar.getDisplayNames(field, Calendar.ALL_STYLES, locale);
-                    if ((index = matchString(text, start, field, map)) > 0) {
+                    if ((index = matchString(text, start, field, map, calb)) > 0) {
                         return index;
                     }
                 }
                 break parsing;
 
-            case 15: // 'h' - HOUR:1-based.  eg, 11PM + 1 hour =>> 12 AM
+            case PATTERN_HOUR1: // 'h' 1-based.  eg, 11PM + 1 hour =>> 12 AM
                 // [We computed 'value' above.]
                 if (value == calendar.getLeastMaximum(Calendar.HOUR)+1) value = 0;
-                calendar.set(Calendar.HOUR, value);
+                calb.set(Calendar.HOUR, value);
                 return pos.index;
 
-            case 17: // 'z' - ZONE_OFFSET
-            case 18: // 'Z' - ZONE_OFFSET
+            case PATTERN_ZONE_NAME:  // 'z'
+            case PATTERN_ZONE_VALUE: // 'Z'
                 // First try to parse generic forms such as GMT-07:00. Do this first
                 // in case localized TimeZoneNames contains the string "GMT"
                 // for a zone; in that case, we don't want to match the first three
@@ -1797,7 +1907,7 @@
                     if ((text.length() - start) >= GMT.length() &&
                         text.regionMatches(true, start, GMT, 0, GMT.length())) {
                         int num;
-                        calendar.set(Calendar.DST_OFFSET, 0);
+                        calb.set(Calendar.DST_OFFSET, 0);
                         pos.index = start + GMT.length();
 
                         try { // try-catch for "GMT" only time zone string
@@ -1810,8 +1920,8 @@
                         }
                         catch(StringIndexOutOfBoundsException e) {}
 
-                        if (sign == 0) {        /* "GMT" without offset */
-                            calendar.set(Calendar.ZONE_OFFSET, 0);
+                        if (sign == 0) {    /* "GMT" without offset */
+                            calb.set(Calendar.ZONE_OFFSET, 0);
                             return pos.index;
                         }
 
@@ -1875,7 +1985,7 @@
                                 sign = -1;
                             } else {
                                 // Try parsing the text as a time zone name (abbr).
-                                int i = subParseZoneString(text, pos.index);
+                                int i = subParseZoneString(text, pos.index, calb);
                                 if (i != 0) {
                                     return i;
                                 }
@@ -1933,24 +2043,112 @@
                     // arrive here if the form GMT+/-... or an RFC 822 form was seen.
                     if (sign != 0) {
                         offset *= MILLIS_PER_MINUTE * sign;
-                        calendar.set(Calendar.ZONE_OFFSET, offset);
-                        calendar.set(Calendar.DST_OFFSET, 0);
+                        calb.set(Calendar.ZONE_OFFSET, offset).set(Calendar.DST_OFFSET, 0);
+                        return ++pos.index;
+                    }
+                }
+                break parsing;
+
+            case PATTERN_ISO_ZONE:   // 'X'
+                {
+                    int sign = 0;
+                    int offset = 0;
+
+                    iso8601: {
+                        try {
+                            char c = text.charAt(pos.index);
+                            if (c == 'Z') {
+                                calb.set(Calendar.ZONE_OFFSET, 0).set(Calendar.DST_OFFSET, 0);
+                                return ++pos.index;
+                            }
+
+                            // parse text as "+/-hh[[:]mm]" based on count
+                            if (c == '+') {
+                                sign = 1;
+                            } else if (c == '-') {
+                                sign = -1;
+                            }
+                            // Look for hh.
+                            int hours = 0;
+                            c = text.charAt(++pos.index);
+                            if (c < '0' || c > '9') { /* must be from '0' to '9'. */
+                                break parsing;
+                            }
+                            hours = c - '0';
+                            c = text.charAt(++pos.index);
+                            if (c < '0' || c > '9') { /* must be from '0' to '9'. */
+                                break parsing;
+                            }
+                            hours *= 10;
+                            hours += c - '0';
+                            if (hours > 23) {
+                                break parsing;
+                            }
+
+                            if (count == 1) { // "X"
+                                offset = hours * 60;
+                                break iso8601;
+                            }
+
+                            c = text.charAt(++pos.index);
+                            // Skip ':' if "XXX"
+                            if (c == ':') {
+                                if (count == 2) {
+                                    break parsing;
+                                }
+                                c = text.charAt(++pos.index);
+                            } else {
+                                if (count == 3) {
+                                    // missing ':'
+                                    break parsing;
+                                }
+                            }
+
+                            // Look for mm.
+                            int minutes = 0;
+                            if (c < '0' || c > '9') { /* must be from '0' to '9'. */
+                                break parsing;
+                            }
+                            minutes = c - '0';
+                            c = text.charAt(++pos.index);
+                            if (c < '0' || c > '9') { /* must be from '0' to '9'. */
+                                break parsing;
+                            }
+                            minutes *= 10;
+                            minutes += c - '0';
+
+                            if (minutes > 59) {
+                                break parsing;
+                            }
+
+                            offset = hours * 60 + minutes;
+                        } catch (StringIndexOutOfBoundsException e) {
+                            break parsing;
+                        }
+                    }
+
+                    // Do the final processing for both of the above cases.  We only
+                    // arrive here if the form GMT+/-... or an RFC 822 form was seen.
+                    if (sign != 0) {
+                        offset *= MILLIS_PER_MINUTE * sign;
+                        calb.set(Calendar.ZONE_OFFSET, offset).set(Calendar.DST_OFFSET, 0);
                         return ++pos.index;
                     }
                 }
                 break parsing;
 
             default:
-                // case 3: // 'd' - DATE
-                // case 5: // 'H' - HOUR_OF_DAY:0-based.  eg, 23:59 + 1 hour =>> 00:59
-                // case 6: // 'm' - MINUTE
-                // case 7: // 's' - SECOND
-                // case 8: // 'S' - MILLISECOND
-                // case 10: // 'D' - DAY_OF_YEAR
-                // case 11: // 'F' - DAY_OF_WEEK_IN_MONTH
-                // case 12: // 'w' - WEEK_OF_YEAR
-                // case 13: // 'W' - WEEK_OF_MONTH
-                // case 16: // 'K' - HOUR: 0-based.  eg, 11PM + 1 hour =>> 0 AM
+         // case PATTERN_DAY_OF_MONTH:         // 'd'
+         // case PATTERN_HOUR_OF_DAY0:         // 'H' 0-based.  eg, 23:59 + 1 hour =>> 00:59
+         // case PATTERN_MINUTE:               // 'm'
+         // case PATTERN_SECOND:               // 's'
+         // case PATTERN_MILLISECOND:          // 'S'
+         // case PATTERN_DAY_OF_YEAR:          // 'D'
+         // case PATTERN_DAY_OF_WEEK_IN_MONTH: // 'F'
+         // case PATTERN_WEEK_OF_YEAR:         // 'w'
+         // case PATTERN_WEEK_OF_MONTH:        // 'W'
+         // case PATTERN_HOUR0:                // 'K' 0-based.  eg, 11PM + 1 hour =>> 0 AM
+         // case PATTERN_ISO_DAY_OF_WEEK:      // 'u' (pseudo field);
 
                 // Handle "generic" fields
                 if (obeyCount) {
@@ -1973,7 +2171,7 @@
                         pos.index--;
                     }
 
-                    calendar.set(field, value);
+                    calb.set(field, value);
                     return pos.index;
                 }
                 break parsing;
@@ -2020,11 +2218,18 @@
                     inQuote = true;
                 else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
                     int ci = from.indexOf(c);
-                    if (ci == -1)
+                    if (ci >= 0) {
+                        // patternChars is longer than localPatternChars due
+                        // to serialization compatibility. The pattern letters
+                        // unsupported by localPatternChars pass through.
+                        if (ci < to.length()) {
+                            c = to.charAt(ci);
+                        }
+                    } else {
                         throw new IllegalArgumentException("Illegal pattern " +
                                                            " character '" +
                                                            c + "'");
-                    c = to.charAt(ci);
+                    }
                 }
             }
             result.append(c);
@@ -2061,7 +2266,7 @@
      * @exception NullPointerException if the given pattern is null
      * @exception IllegalArgumentException if the given pattern is invalid
      */
-    public void applyPattern (String pattern)
+    public void applyPattern(String pattern)
     {
         compiledPattern = compile(pattern);
         this.pattern = pattern;
--- a/src/share/classes/java/util/Calendar.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/util/Calendar.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -119,7 +119,7 @@
  * calculating its time or calendar field values if any out-of-range field
  * value has been set.
  *
- * <h4>First Week</h4>
+ * <h4><a name="first_week">First Week</a></h4>
  *
  * <code>Calendar</code> defines a locale-specific seven day week using two
  * parameters: the first day of the week and the minimal days in first week
@@ -933,7 +933,7 @@
      */
     protected Calendar()
     {
-        this(TimeZone.getDefaultRef(), Locale.getDefault());
+        this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
         sharedZone = true;
     }
 
@@ -962,7 +962,7 @@
      */
     public static Calendar getInstance()
     {
-        Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault());
+        Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
         cal.sharedZone = true;
         return cal;
     }
@@ -977,7 +977,7 @@
      */
     public static Calendar getInstance(TimeZone zone)
     {
-        return createCalendar(zone, Locale.getDefault());
+        return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -1013,19 +1013,30 @@
     private static Calendar createCalendar(TimeZone zone,
                                            Locale aLocale)
     {
-        // If the specified locale is a Thai locale, returns a BuddhistCalendar
-        // instance.
-        if ("th".equals(aLocale.getLanguage())
-            && ("TH".equals(aLocale.getCountry()))) {
-            return new sun.util.BuddhistCalendar(zone, aLocale);
-        } else if ("JP".equals(aLocale.getVariant())
-                   && "JP".equals(aLocale.getCountry())
-                   && "ja".equals(aLocale.getLanguage())) {
-            return new JapaneseImperialCalendar(zone, aLocale);
+        Calendar cal = null;
+
+        String caltype = aLocale.getUnicodeLocaleType("ca");
+        if (caltype == null) {
+            // Calendar type is not specified.
+            // If the specified locale is a Thai locale,
+            // returns a BuddhistCalendar instance.
+            if ("th".equals(aLocale.getLanguage())
+                    && ("TH".equals(aLocale.getCountry()))) {
+                    cal = new BuddhistCalendar(zone, aLocale);
+            } else {
+                cal = new GregorianCalendar(zone, aLocale);
+            }
+        } else if (caltype.equals("japanese")) {
+            cal = new JapaneseImperialCalendar(zone, aLocale);
+        } else if (caltype.equals("buddhist")) {
+            cal = new BuddhistCalendar(zone, aLocale);
+        } else {
+            // Unsupported calendar type.
+            // Use Gregorian calendar as a fallback.
+            cal = new GregorianCalendar(zone, aLocale);
         }
 
-        // else create the default calendar
-        return new GregorianCalendar(zone, aLocale);
+        return cal;
     }
 
     /**
@@ -2196,6 +2207,101 @@
     }
 
     /**
+     * Returns whether this {@code Calendar} supports week dates.
+     *
+     * <p>The default implementation of this method returns {@code false}.
+     *
+     * @return {@code true} if this {@code Calendar} supports week dates;
+     *         {@code false} otherwise.
+     * @see #getWeekYear()
+     * @see #setWeekDate(int,int,int)
+     * @see #getWeeksInWeekYear()
+     * @since 1.7
+     */
+    public boolean isWeekDateSupported() {
+        return false;
+    }
+
+    /**
+     * Returns the week year represented by this {@code Calendar}. The
+     * week year is in sync with the week cycle. The {@linkplain
+     * #getFirstDayOfWeek() first day of the first week} is the first
+     * day of the week year.
+     *
+     * <p>The default implementation of this method throws an
+     * {@link UnsupportedOperationException}.
+     *
+     * @return the week year of this {@code Calendar}
+     * @exception UnsupportedOperationException
+     *            if any week year numbering isn't supported
+     *            in this {@code Calendar}.
+     * @see #isWeekDateSupported()
+     * @see #getFirstDayOfWeek()
+     * @see #getMinimalDaysInFirstWeek()
+     * @since 1.7
+     */
+    public int getWeekYear() {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Sets the date of this {@code Calendar} with the the given date
+     * specifiers - week year, week of year, and day of week.
+     *
+     * <p>Unlike the {@code set} method, all of the calendar fields
+     * and {@code time} values are calculated upon return.
+     *
+     * <p>If {@code weekOfYear} is out of the valid week-of-year range
+     * in {@code weekYear}, the {@code weekYear} and {@code
+     * weekOfYear} values are adjusted in lenient mode, or an {@code
+     * IllegalArgumentException} is thrown in non-lenient mode.
+     *
+     * <p>The default implementation of this method throws an
+     * {@code UnsupportedOperationException}.
+     *
+     * @param weekYear   the week year
+     * @param weekOfYear the week number based on {@code weekYear}
+     * @param dayOfWeek  the day of week value: one of the constants
+     *                   for the {@link #DAY_OF_WEEK} field: {@link
+     *                   #SUNDAY}, ..., {@link #SATURDAY}.
+     * @exception IllegalArgumentException
+     *            if any of the given date specifiers is invalid
+     *            or any of the calendar fields are inconsistent
+     *            with the given date specifiers in non-lenient mode
+     * @exception UnsupportedOperationException
+     *            if any week year numbering isn't supported in this
+     *            {@code Calendar}.
+     * @see #isWeekDateSupported()
+     * @see #getFirstDayOfWeek()
+     * @see #getMinimalDaysInFirstWeek()
+     * @since 1.7
+     */
+    public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Returns the number of weeks in the week year represented by this
+     * {@code Calendar}.
+     *
+     * <p>The default implementation of this method throws an
+     * {@code UnsupportedOperationException}.
+     *
+     * @return the number of weeks in the week year.
+     * @exception UnsupportedOperationException
+     *            if any week year numbering isn't supported in this
+     *            {@code Calendar}.
+     * @see #WEEK_OF_YEAR
+     * @see #isWeekDateSupported()
+     * @see #getWeekYear()
+     * @see #getActualMaximum(int)
+     * @since 1.7
+     */
+    public int getWeeksInWeekYear() {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
      * Returns the minimum value for the given calendar field of this
      * <code>Calendar</code> instance. The minimum value is defined as
      * the smallest value returned by the {@link #get(int) get} method
--- a/src/share/classes/java/util/Currency.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/util/Currency.java	Sat Sep 25 12:00:05 2010 -0700
@@ -452,7 +452,7 @@
      * @return the symbol of this currency for the default locale
      */
     public String getSymbol() {
-        return getSymbol(Locale.getDefault());
+        return getSymbol(Locale.getDefault(Locale.Category.DISPLAY));
     }
 
     /**
@@ -528,7 +528,7 @@
      * @since 1.7
      */
     public String getDisplayName() {
-        return getDisplayName(Locale.getDefault());
+        return getDisplayName(Locale.getDefault(Locale.Category.DISPLAY));
     }
 
     /**
--- a/src/share/classes/java/util/Formatter.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/util/Formatter.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1866,7 +1866,7 @@
      * virtual machine.
      */
     public Formatter() {
-        init(new StringBuilder(), Locale.getDefault());
+        init(new StringBuilder(), Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -1882,7 +1882,7 @@
     public Formatter(Appendable a) {
         if (a == null)
             a = new StringBuilder();
-        init(a, Locale.getDefault());
+        init(a, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -1949,7 +1949,7 @@
      */
     public Formatter(String fileName) throws FileNotFoundException {
         init(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
-             Locale.getDefault());
+             Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -1985,7 +1985,7 @@
     public Formatter(String fileName, String csn)
         throws FileNotFoundException, UnsupportedEncodingException
     {
-        this(fileName, csn, Locale.getDefault());
+        this(fileName, csn, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -2057,7 +2057,7 @@
      */
     public Formatter(File file) throws FileNotFoundException {
         init(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
-             Locale.getDefault());
+             Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -2093,7 +2093,7 @@
     public Formatter(File file, String csn)
         throws FileNotFoundException, UnsupportedEncodingException
     {
-        this(file, csn, Locale.getDefault());
+        this(file, csn, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -2152,7 +2152,7 @@
     public Formatter(PrintStream ps) {
         if (ps == null)
             throw new NullPointerException();
-        init((Appendable)ps, Locale.getDefault());
+        init((Appendable)ps, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -2171,7 +2171,7 @@
      */
     public Formatter(OutputStream os) {
         init(new BufferedWriter(new OutputStreamWriter(os)),
-             Locale.getDefault());
+             Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -2195,7 +2195,7 @@
     public Formatter(OutputStream os, String csn)
         throws UnsupportedEncodingException
     {
-        this(os, csn, Locale.getDefault());
+        this(os, csn, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
--- a/src/share/classes/java/util/GregorianCalendar.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/util/GregorianCalendar.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -88,23 +88,49 @@
  * adjustment may be made if desired for dates that are prior to the Gregorian
  * changeover and which fall between January 1 and March 24.
  *
- * <p>Values calculated for the <code>WEEK_OF_YEAR</code> field range from 1 to
- * 53.  Week 1 for a year is the earliest seven day period starting on
- * <code>getFirstDayOfWeek()</code> that contains at least
- * <code>getMinimalDaysInFirstWeek()</code> days from that year.  It thus
- * depends on the values of <code>getMinimalDaysInFirstWeek()</code>,
- * <code>getFirstDayOfWeek()</code>, and the day of the week of January 1.
- * Weeks between week 1 of one year and week 1 of the following year are
- * numbered sequentially from 2 to 52 or 53 (as needed).
-
- * <p>For example, January 1, 1998 was a Thursday.  If
- * <code>getFirstDayOfWeek()</code> is <code>MONDAY</code> and
- * <code>getMinimalDaysInFirstWeek()</code> is 4 (these are the values
- * reflecting ISO 8601 and many national standards), then week 1 of 1998 starts
- * on December 29, 1997, and ends on January 4, 1998.  If, however,
- * <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>, then week 1 of 1998
- * starts on January 4, 1998, and ends on January 10, 1998; the first three days
- * of 1998 then are part of week 53 of 1997.
+ * <h4><a name="week_and_year">Week Of Year and Week Year</a></h4>
+ *
+ * <p>Values calculated for the {@link Calendar#WEEK_OF_YEAR
+ * WEEK_OF_YEAR} field range from 1 to 53. The first week of a
+ * calendar year is the earliest seven day period starting on {@link
+ * Calendar#getFirstDayOfWeek() getFirstDayOfWeek()} that contains at
+ * least {@link Calendar#getMinimalDaysInFirstWeek()
+ * getMinimalDaysInFirstWeek()} days from that year. It thus depends
+ * on the values of {@code getMinimalDaysInFirstWeek()}, {@code
+ * getFirstDayOfWeek()}, and the day of the week of January 1. Weeks
+ * between week 1 of one year and week 1 of the following year
+ * (exclusive) are numbered sequentially from 2 to 52 or 53 (except
+ * for year(s) involved in the Julian-Gregorian transition).
+ *
+ * <p>The {@code getFirstDayOfWeek()} and {@code
+ * getMinimalDaysInFirstWeek()} values are initialized using
+ * locale-dependent resources when constructing a {@code
+ * GregorianCalendar}. <a name="iso8601_compatible_setting">The week
+ * determination is compatible</a> with the ISO 8601 standard when {@code
+ * getFirstDayOfWeek()} is {@code MONDAY} and {@code
+ * getMinimalDaysInFirstWeek()} is 4, which values are used in locales
+ * where the standard is preferred. These values can explicitly be set by
+ * calling {@link Calendar#setFirstDayOfWeek(int) setFirstDayOfWeek()} and
+ * {@link Calendar#setMinimalDaysInFirstWeek(int)
+ * setMinimalDaysInFirstWeek()}.
+ *
+ * <p>A <a name="week_year"><em>week year</em></a> is in sync with a
+ * {@code WEEK_OF_YEAR} cycle. All weeks between the first and last
+ * weeks (inclusive) have the same <em>week year</em> value.
+ * Therefore, the first and last days of a week year may have
+ * different calendar year values.
+ *
+ * <p>For example, January 1, 1998 is a Thursday. If {@code
+ * getFirstDayOfWeek()} is {@code MONDAY} and {@code
+ * getMinimalDaysInFirstWeek()} is 4 (ISO 8601 standard compatible
+ * setting), then week 1 of 1998 starts on December 29, 1997, and ends
+ * on January 4, 1998. The week year is 1998 for the last three days
+ * of calendar year 1997. If, however, {@code getFirstDayOfWeek()} is
+ * {@code SUNDAY}, then week 1 of 1998 starts on January 4, 1998, and
+ * ends on January 10, 1998; the first three days of 1998 then are
+ * part of week 53 of 1997 and their week year is 1997.
+ *
+ * <h4>Week Of Month</h4>
  *
  * <p>Values calculated for the <code>WEEK_OF_MONTH</code> field range from 0
  * to 6.  Week 1 of a month (the days with <code>WEEK_OF_MONTH =
@@ -124,7 +150,9 @@
  * <code>getMinimalDaysInFirstWeek()</code> is changed to 3, then January 1
  * through January 3 have a <code>WEEK_OF_MONTH</code> of 1.
  *
- * <p>The <code>clear</code> methods set calendar field(s)
+ * <h4>Default Fields Values</h4>
+ *
+ * <p>The <code>clear</code> method sets calendar field(s)
  * undefined. <code>GregorianCalendar</code> uses the following
  * default value for each calendar field if its value is undefined.
  *
@@ -555,7 +583,7 @@
      * in the default time zone with the default locale.
      */
     public GregorianCalendar() {
-        this(TimeZone.getDefaultRef(), Locale.getDefault());
+        this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
         setZoneShared(true);
     }
 
@@ -566,7 +594,7 @@
      * @param zone the given time zone.
      */
     public GregorianCalendar(TimeZone zone) {
-        this(zone, Locale.getDefault());
+        this(zone, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -1625,6 +1653,13 @@
      * is 29 because 2004 is a leap year, and if the date of this
      * instance is February 1, 2005, it's 28.
      *
+     * <p>This method calculates the maximum value of {@link
+     * Calendar#WEEK_OF_YEAR WEEK_OF_YEAR} based on the {@link
+     * Calendar#YEAR YEAR} (calendar year) value, not the <a
+     * href="#week_year">week year</a>. Call {@link
+     * #getWeeksInWeekYear()} to get the maximum value of {@code
+     * WEEK_OF_YEAR} in the week year of this {@code GregorianCalendar}.
+     *
      * @param field the calendar field
      * @return the maximum of the given field for the time value of
      * this <code>GregorianCalendar</code>
@@ -1742,8 +1777,13 @@
                 if (gc == this) {
                     gc = (GregorianCalendar) gc.clone();
                 }
-                gc.set(DAY_OF_YEAR, getActualMaximum(DAY_OF_YEAR));
+                int maxDayOfYear = getActualMaximum(DAY_OF_YEAR);
+                gc.set(DAY_OF_YEAR, maxDayOfYear);
                 value = gc.get(WEEK_OF_YEAR);
+                if (internalGet(YEAR) != gc.getWeekYear()) {
+                    gc.set(DAY_OF_YEAR, maxDayOfYear - 7);
+                    value = gc.get(WEEK_OF_YEAR);
+                }
             }
             break;
 
@@ -1934,46 +1974,241 @@
         }
     }
 
-//////////////////////
-// Proposed public API
-//////////////////////
+    /**
+     * Returns {@code true} indicating this {@code GregorianCalendar}
+     * supports week dates.
+     *
+     * @return {@code true} (always)
+     * @see #getWeekYear()
+     * @see #setWeekDate(int,int,int)
+     * @see #getWeeksInWeekYear()
+     * @since 1.7
+     */
+    @Override
+    public final boolean isWeekDateSupported() {
+        return true;
+    }
 
     /**
-     * Returns the year that corresponds to the <code>WEEK_OF_YEAR</code> field.
-     * This may be one year before or after the Gregorian or Julian year stored
-     * in the <code>YEAR</code> field.  For example, January 1, 1999 is considered
-     * Friday of week 53 of 1998 (if minimal days in first week is
-     * 2 or less, and the first day of the week is Sunday).  Given
-     * these same settings, the ISO year of January 1, 1999 is
-     * 1998.
+     * Returns the <a href="#week_year">week year</a> represented by this
+     * {@code GregorianCalendar}. The dates in the weeks between 1 and the
+     * maximum week number of the week year have the same week year value
+     * that may be one year before or after the {@link Calendar#YEAR YEAR}
+     * (calendar year) value.
      *
-     * <p>This method calls {@link Calendar#complete} before
-     * calculating the week-based year.
+     * <p>This method calls {@link Calendar#complete()} before
+     * calculating the week year.
      *
-     * @return the year corresponding to the <code>WEEK_OF_YEAR</code> field, which
-     * may be one year before or after the <code>YEAR</code> field.
-     * @see #YEAR
-     * @see #WEEK_OF_YEAR
+     * @return the week year represented by this {@code GregorianCalendar}.
+     *         If the {@link Calendar#ERA ERA} value is {@link #BC}, the year is
+     *         represented by 0 or a negative number: BC 1 is 0, BC 2
+     *         is -1, BC 3 is -2, and so on.
+     * @throws IllegalArgumentException
+     *         if any of the calendar fields is invalid in non-lenient mode.
+     * @see #isWeekDateSupported()
+     * @see #getWeeksInWeekYear()
+     * @see Calendar#getFirstDayOfWeek()
+     * @see Calendar#getMinimalDaysInFirstWeek()
+     * @since 1.7
      */
-    /*
-    public int getWeekBasedYear() {
-        complete();
-        // TODO: Below doesn't work for gregorian cutover...
-        int weekOfYear = internalGet(WEEK_OF_YEAR);
-        int year = internalGet(YEAR);
-        if (internalGet(MONTH) == Calendar.JANUARY) {
-            if (weekOfYear >= 52) {
+    @Override
+    public int getWeekYear() {
+        int year = get(YEAR); // implicitly calls complete()
+        if (internalGetEra() == BCE) {
+            year = 1 - year;
+        }
+
+        // Fast path for the Gregorian calendar years that are never
+        // affected by the Julian-Gregorian transition
+        if (year > gregorianCutoverYear + 1) {
+            int weekOfYear = internalGet(WEEK_OF_YEAR);
+            if (internalGet(MONTH) == JANUARY) {
+                if (weekOfYear >= 52) {
+                    --year;
+                }
+            } else {
+                if (weekOfYear == 1) {
+                    ++year;
+                }
+            }
+            return year;
+        }
+
+        // General (slow) path
+        int dayOfYear = internalGet(DAY_OF_YEAR);
+        int maxDayOfYear = getActualMaximum(DAY_OF_YEAR);
+        int minimalDays = getMinimalDaysInFirstWeek();
+
+        // Quickly check the possibility of year adjustments before
+        // cloning this GregorianCalendar.
+        if (dayOfYear > minimalDays && dayOfYear < (maxDayOfYear - 6)) {
+            return year;
+        }
+
+        // Create a clone to work on the calculation
+        GregorianCalendar cal = (GregorianCalendar) clone();
+        cal.setLenient(true);
+        // Use GMT so that intermediate date calculations won't
+        // affect the time of day fields.
+        cal.setTimeZone(TimeZone.getTimeZone("GMT"));
+        // Go to the first day of the year, which is usually January 1.
+        cal.set(DAY_OF_YEAR, 1);
+        cal.complete();
+
+        // Get the first day of the first day-of-week in the year.
+        int delta = getFirstDayOfWeek() - cal.get(DAY_OF_WEEK);
+        if (delta != 0) {
+            if (delta < 0) {
+                delta += 7;
+            }
+            cal.add(DAY_OF_YEAR, delta);
+        }
+        int minDayOfYear = cal.get(DAY_OF_YEAR);
+        if (dayOfYear < minDayOfYear) {
+            if (minDayOfYear <= minimalDays) {
                 --year;
             }
         } else {
-            if (weekOfYear == 1) {
-                ++year;
+            cal.set(YEAR, year + 1);
+            cal.set(DAY_OF_YEAR, 1);
+            cal.complete();
+            int del = getFirstDayOfWeek() - cal.get(DAY_OF_WEEK);
+            if (del != 0) {
+                if (del < 0) {
+                    del += 7;
+                }
+                cal.add(DAY_OF_YEAR, del);
+            }
+            minDayOfYear = cal.get(DAY_OF_YEAR) - 1;
+            if (minDayOfYear == 0) {
+                minDayOfYear = 7;
+            }
+            if (minDayOfYear >= minimalDays) {
+                int days = maxDayOfYear - dayOfYear + 1;
+                if (days <= (7 - minDayOfYear)) {
+                    ++year;
+                }
             }
         }
         return year;
     }
-    */
 
+    /**
+     * Sets this {@code GregorianCalendar} to the date given by the
+     * date specifiers - <a href="#week_year">{@code weekYear}</a>,
+     * {@code weekOfYear}, and {@code dayOfWeek}. {@code weekOfYear}
+     * follows the <a href="#week_and_year">{@code WEEK_OF_YEAR}
+     * numbering</a>.  The {@code dayOfWeek} value must be one of the
+     * {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} values: {@link
+     * Calendar#SUNDAY SUNDAY} to {@link Calendar#SATURDAY SATURDAY}.
+     *
+     * <p>Note that the numeric day-of-week representation differs from
+     * the ISO 8601 standard, and that the {@code weekOfYear}
+     * numbering is compatible with the standard when {@code
+     * getFirstDayOfWeek()} is {@code MONDAY} and {@code
+     * getMinimalDaysInFirstWeek()} is 4.
+     *
+     * <p>Unlike the {@code set} method, all of the calendar fields
+     * and the instant of time value are calculated upon return.
+     *
+     * <p>If {@code weekOfYear} is out of the valid week-of-year
+     * range in {@code weekYear}, the {@code weekYear}
+     * and {@code weekOfYear} values are adjusted in lenient
+     * mode, or an {@code IllegalArgumentException} is thrown in
+     * non-lenient mode.
+     *
+     * @param weekYear    the week year
+     * @param weekOfYear  the week number based on {@code weekYear}
+     * @param dayOfWeek   the day of week value: one of the constants
+     *                    for the {@link #DAY_OF_WEEK DAY_OF_WEEK} field:
+     *                    {@link Calendar#SUNDAY SUNDAY}, ...,
+     *                    {@link Calendar#SATURDAY SATURDAY}.
+     * @exception IllegalArgumentException
+     *            if any of the given date specifiers is invalid,
+     *            or if any of the calendar fields are inconsistent
+     *            with the given date specifiers in non-lenient mode
+     * @see GregorianCalendar#isWeekDateSupported()
+     * @see Calendar#getFirstDayOfWeek()
+     * @see Calendar#getMinimalDaysInFirstWeek()
+     * @since 1.7
+     */
+    @Override
+    public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
+        if (dayOfWeek < SUNDAY || dayOfWeek > SATURDAY) {
+            throw new IllegalArgumentException("invalid dayOfWeek: " + dayOfWeek);
+        }
+
+        // To avoid changing the time of day fields by date
+        // calculations, use a clone with the GMT time zone.
+        GregorianCalendar gc = (GregorianCalendar) clone();
+        gc.setLenient(true);
+        int era = gc.get(ERA);
+        gc.clear();
+        gc.setTimeZone(TimeZone.getTimeZone("GMT"));
+        gc.set(ERA, era);
+        gc.set(YEAR, weekYear);
+        gc.set(WEEK_OF_YEAR, 1);
+        gc.set(DAY_OF_WEEK, getFirstDayOfWeek());
+        int days = dayOfWeek - getFirstDayOfWeek();
+        if (days < 0) {
+            days += 7;
+        }
+        days += 7 * (weekOfYear - 1);
+        if (days != 0) {
+            gc.add(DAY_OF_YEAR, days);
+        } else {
+            gc.complete();
+        }
+
+        if (!isLenient() &&
+            (gc.getWeekYear() != weekYear
+             || gc.internalGet(WEEK_OF_YEAR) != weekOfYear
+             || gc.internalGet(DAY_OF_WEEK) != dayOfWeek)) {
+            throw new IllegalArgumentException();
+        }
+
+        set(ERA, gc.internalGet(ERA));
+        set(YEAR, gc.internalGet(YEAR));
+        set(MONTH, gc.internalGet(MONTH));
+        set(DAY_OF_MONTH, gc.internalGet(DAY_OF_MONTH));
+
+        // to avoid throwing an IllegalArgumentException in
+        // non-lenient, set WEEK_OF_YEAR internally
+        internalSet(WEEK_OF_YEAR, weekOfYear);
+        complete();
+    }
+
+    /**
+     * Returns the number of weeks in the <a href="#week_year">week year</a>
+     * represented by this {@code GregorianCalendar}.
+     *
+     * <p>For example, if this {@code GregorianCalendar}'s date is
+     * December 31, 2008 with <a href="#iso8601_compatible_setting">the ISO
+     * 8601 compatible setting</a>, this method will return 53 for the
+     * period: December 29, 2008 to January 3, 2010 while {@link
+     * #getActualMaximum(int) getActualMaximum(WEEK_OF_YEAR)} will return
+     * 52 for the period: December 31, 2007 to December 28, 2008.
+     *
+     * @return the number of weeks in the week year.
+     * @see Calendar#WEEK_OF_YEAR
+     * @see #getWeekYear()
+     * @see #getActualMaximum(int)
+     * @since 1.7
+     */
+    public int getWeeksInWeekYear() {
+        GregorianCalendar gc = getNormalizedCalendar();
+        int weekYear = gc.getWeekYear();
+        if (weekYear == gc.internalGet(YEAR)) {
+            return gc.getActualMaximum(WEEK_OF_YEAR);
+        }
+
+        // Use the 2nd week for calculating the max of WEEK_OF_YEAR
+        if (gc == this) {
+            gc = (GregorianCalendar) gc.clone();
+        }
+        gc.setWeekDate(weekYear, 2, internalGet(DAY_OF_WEEK));
+        return gc.getActualMaximum(WEEK_OF_YEAR);
+    }
 
 /////////////////////////////
 // Time => Fields computation
@@ -2178,7 +2413,7 @@
             // If we are in the cutover year, we need some special handling.
             if (normalizedYear == cutoverYear) {
                 // Need to take care of the "missing" days.
-                if (getCutoverCalendarSystem() == jcal) {
+                if (gregorianCutoverYearJulian <= gregorianCutoverYear) {
                     // We need to find out where we are. The cutover
                     // gap could even be more than one year.  (One
                     // year difference in ~48667 years.)
@@ -2208,27 +2443,36 @@
                 // December 31, which is not always true in
                 // GregorianCalendar.
                 long fixedDec31 = fixedDateJan1 - 1;
-                long prevJan1;
+                long prevJan1  = fixedDateJan1 - 365;
                 if (normalizedYear > (cutoverYear + 1)) {
-                    prevJan1 = fixedDateJan1 - 365;
                     if (CalendarUtils.isGregorianLeapYear(normalizedYear - 1)) {
                         --prevJan1;
                     }
+                } else if (normalizedYear <= gregorianCutoverYearJulian) {
+                    if (CalendarUtils.isJulianLeapYear(normalizedYear - 1)) {
+                        --prevJan1;
+                    }
                 } else {
                     BaseCalendar calForJan1 = calsys;
-                    int prevYear = normalizedYear - 1;
-                    if (prevYear == cutoverYear) {
+                    //int prevYear = normalizedYear - 1;
+                    int prevYear = getCalendarDate(fixedDec31).getNormalizedYear();
+                    if (prevYear == gregorianCutoverYear) {
                         calForJan1 = getCutoverCalendarSystem();
-                    }
-                    prevJan1 = calForJan1.getFixedDate(prevYear,
-                                                       BaseCalendar.JANUARY,
-                                                       1,
-                                                       null);
-                    while (prevJan1 > fixedDec31) {
-                        prevJan1 = getJulianCalendarSystem().getFixedDate(--prevYear,
-                                                                    BaseCalendar.JANUARY,
-                                                                    1,
-                                                                    null);
+                        if (calForJan1 == jcal) {
+                            prevJan1 = calForJan1.getFixedDate(prevYear,
+                                                               BaseCalendar.JANUARY,
+                                                               1,
+                                                               null);
+                        } else {
+                            prevJan1 = gregorianCutoverDate;
+                            calForJan1 = gcal;
+                        }
+                    } else if (prevYear <= gregorianCutoverYearJulian) {
+                        calForJan1 = getJulianCalendarSystem();
+                        prevJan1 = calForJan1.getFixedDate(prevYear,
+                                                           BaseCalendar.JANUARY,
+                                                           1,
+                                                           null);
                     }
                 }
                 weekOfYear = getWeekNumber(prevJan1, fixedDec31);
@@ -2260,14 +2504,20 @@
                     if (nextYear == gregorianCutoverYear) {
                         calForJan1 = getCutoverCalendarSystem();
                     }
-                    long nextJan1 = calForJan1.getFixedDate(nextYear,
-                                                            BaseCalendar.JANUARY,
-                                                            1,
-                                                            null);
-                    if (nextJan1 < fixedDate) {
+
+                    long nextJan1;
+                    if (nextYear > gregorianCutoverYear
+                        || gregorianCutoverYearJulian == gregorianCutoverYear
+                        || nextYear == gregorianCutoverYearJulian) {
+                        nextJan1 = calForJan1.getFixedDate(nextYear,
+                                                           BaseCalendar.JANUARY,
+                                                           1,
+                                                           null);
+                    } else {
                         nextJan1 = gregorianCutoverDate;
                         calForJan1 = gcal;
                     }
+
                     long nextJan1st = calForJan1.getDayOfWeekDateOnOrBefore(nextJan1 + 6,
                                                                             getFirstDayOfWeek());
                     int ndays = (int)(nextJan1st - nextJan1);
@@ -2409,10 +2659,24 @@
                 }
                 gfd = jfd;
             } else {
+                jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask);
                 gfd = fixedDate + getFixedDate(gcal, year, fieldMask);
-                jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask);
             }
+
             // Now we have to determine which calendar date it is.
+
+            // If the date is relative from the beginning of the year
+            // in the Julian calendar, then use jfd;
+            if (isFieldSet(fieldMask, DAY_OF_YEAR) || isFieldSet(fieldMask, WEEK_OF_YEAR)) {
+                if (gregorianCutoverYear == gregorianCutoverYearJulian) {
+                    fixedDate = jfd;
+                    break calculateFixedDate;
+                } else if (year == gregorianCutoverYear) {
+                    fixedDate = gfd;
+                    break calculateFixedDate;
+                }
+            }
+
             if (gfd >= gregorianCutoverDate) {
                 if (jfd >= gregorianCutoverDate) {
                     fixedDate = gfd;
@@ -2494,9 +2758,10 @@
                     continue;
                 }
                 if (originalFields[field] != internalGet(field)) {
+                    String s = originalFields[field] + " -> " + internalGet(field);
                     // Restore the original field values
                     System.arraycopy(originalFields, 0, fields, 0, fields.length);
-                    throw new IllegalArgumentException(getFieldName(field));
+                    throw new IllegalArgumentException(getFieldName(field) + ": " + s);
                 }
             }
         }
@@ -2669,9 +2934,7 @@
      * method returns Gregorian. Otherwise, Julian.
      */
     private BaseCalendar getCutoverCalendarSystem() {
-        CalendarDate date = getGregorianCutoverDate();
-        if (date.getMonth() == BaseCalendar.JANUARY
-            && date.getDayOfMonth() == 1) {
+        if (gregorianCutoverYearJulian < gregorianCutoverYear) {
             return gcal;
         }
         return getJulianCalendarSystem();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/util/IllformedLocaleException.java	Sat Sep 25 12:00:05 2010 -0700
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * 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.
+ */
+
+/*
+ *******************************************************************************
+ * Copyright (C) 2009-2010, International Business Machines Corporation and    *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+
+package java.util;
+
+/**
+ * Thrown by methods in {@link Locale} and {@link Locale.Builder} to
+ * indicate that an argument is not a well-formed BCP 47 tag.
+ *
+ * @see Locale
+ * @since 1.7
+ */
+public class IllformedLocaleException extends RuntimeException {
+
+    private static final long serialVersionUID = -5245986824925681401L;
+
+    private int _errIdx = -1;
+
+    /**
+     * Constructs a new <code>IllformedLocaleException</code> with no
+     * detail message and -1 as the error index.
+     */
+    public IllformedLocaleException() {
+        super();
+    }
+
+    /**
+     * Constructs a new <code>IllformedLocaleException</code> with the
+     * given message and -1 as the error index.
+     *
+     * @param message the message
+     */
+    public IllformedLocaleException(String message) {
+        super(message);
+    }
+
+    /**
+     * Constructs a new <code>IllformedLocaleException</code> with the
+     * given message and the error index.  The error index is the approximate
+     * offset from the start of the ill-formed value to the point where the
+     * parse first detected an error.  A negative error index value indicates
+     * either the error index is not applicable or unknown.
+     *
+     * @param message the message
+     * @param errorIndex the index
+     */
+    public IllformedLocaleException(String message, int errorIndex) {
+        super(message + ((errorIndex < 0) ? "" : " [at index " + errorIndex + "]"));
+        _errIdx = errorIndex;
+    }
+
+    /**
+     * Returns the index where the error was found. A negative value indicates
+     * either the error index is not applicable or unknown.
+     *
+     * @return the error index
+     */
+    public int getErrorIndex() {
+        return _errIdx;
+    }
+}
--- a/src/share/classes/java/util/Locale.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/util/Locale.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,86 +40,240 @@
 
 package java.util;
 
-import java.io.*;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamField;
+import java.io.Serializable;
 import java.security.AccessController;
 import java.text.MessageFormat;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
 import java.util.spi.LocaleNameProvider;
-import java.util.spi.LocaleServiceProvider;
+
 import sun.security.action.GetPropertyAction;
 import sun.util.LocaleServiceProviderPool;
+import sun.util.locale.AsciiUtil;
+import sun.util.locale.BaseLocale;
+import sun.util.locale.InternalLocaleBuilder;
+import sun.util.locale.LanguageTag;
+import sun.util.locale.LocaleExtensions;
+import sun.util.locale.LocaleObjectCache;
+import sun.util.locale.LocaleSyntaxException;
+import sun.util.locale.ParseStatus;
+import sun.util.locale.UnicodeLocaleExtension;
 import sun.util.resources.LocaleData;
 import sun.util.resources.OpenListResourceBundle;
 
 /**
- *
  * A <code>Locale</code> object represents a specific geographical, political,
  * or cultural region. An operation that requires a <code>Locale</code> to perform
  * its task is called <em>locale-sensitive</em> and uses the <code>Locale</code>
  * to tailor information for the user. For example, displaying a number
- * is a locale-sensitive operation--the number should be formatted
- * according to the customs/conventions of the user's native country,
+ * is a locale-sensitive operation&mdash; the number should be formatted
+ * according to the customs and conventions of the user's native country,
  * region, or culture.
  *
- * <P>
- * Create a <code>Locale</code> object using the constructors in this class:
+ * <p> The <code>Locale</code> class implements identifiers
+ * interchangeable with BCP 47 (IETF BCP 47, "Tags for Identifying
+ * Languages"), with support for the LDML (UTS#35, "Unicode Locale
+ * Data Markup Language") BCP 47-compatible extensions for locale data
+ * exchange.
+ *
+ * <p> A <code>Locale</code> object logically consists of the fields
+ * described below.
+ *
+ * <dl>
+ *   <dt><a name="def_language"/><b>language</b></dt>
+ *
+ *   <dd>ISO 639 alpha-2 or alpha-3 language code, or registered
+ *   language subtags up to 8 alpha letters (for future enhancements).
+ *   When a language has both an alpha-2 code and an alpha-3 code, the
+ *   alpha-2 code must be used.  You can find a full list of valid
+ *   language codes in the IANA Language Subtag Registry (search for
+ *   "Type: language").  The language field is case insensitive, but
+ *   <code>Locale</code> always canonicalizes to lower case.</dd><br>
+ *
+ *   <dd>Well-formed language values have the form
+ *   <code>[a-zA-Z]{2,8}</code>.  Note that this is not the the full
+ *   BCP47 language production, since it excludes extlang.  They are
+ *   not needed since modern three-letter language codes replace
+ *   them.</dd><br>
+ *
+ *   <dd>Example: "en" (English), "ja" (Japanese), "kok" (Konkani)</dd><br>
+ *
+ *   <dt><a name="def_script"/><b>script</b></dt>
+ *
+ *   <dd>ISO 15924 alpha-4 script code.  You can find a full list of
+ *   valid script codes in the IANA Language Subtag Registry (search
+ *   for "Type: script").  The script field is case insensitive, but
+ *   <code>Locale</code> always canonicalizes to title case (the first
+ *   letter is upper case and the rest of the letters are lower
+ *   case).</dd><br>
+ *
+ *   <dd>Well-formed script values have the form
+ *   <code>[a-zA-Z]{4}</code></dd><br>
+ *
+ *   <dd>Example: "Latn" (Latin), "Cyrl" (Cyrillic)</dd><br>
+ *
+ *   <dt><a name="def_region"/><b>country (region)</b></dt>
+ *
+ *   <dd>ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code.
+ *   You can find a full list of valid country and region codes in the
+ *   IANA Language Subtag Registry (search for "Type: region").  The
+ *   country (region) field is case insensitive, but
+ *   <code>Locale</code> always canonicalizes to upper case.</dd><br>
+ *
+ *   <dd>Well-formed country/region values have
+ *   the form <code>[a-zA-Z]{2} | [0-9]{3}</code></dd><br>
+ *
+ *   <dd>Example: "US" (United States), "FR" (France), "029"
+ *   (Caribbean)</dd><br>
+ *
+ *   <dt><a name="def_variant"/><b>variant</b></dt>
+ *
+ *   <dd>Any arbitrary value used to indicate a variation of a
+ *   <code>Locale</code>.  Where there are two or more variant values
+ *   each indicating its own semantics, these values should be ordered
+ *   by importance, with most important first, separated by
+ *   underscore('_').  The variant field is case sensitive.</dd><br>
+ *
+ *   <dd>Note: IETF BCP 47 places syntactic restrictions on variant
+ *   subtags.  Also BCP 47 subtags are strictly used to indicate
+ *   additional variations that define a language or its dialects that
+ *   are not covered by any combinations of language, script and
+ *   region subtags.  You can find a full list of valid variant codes
+ *   in the IANA Language Subtag Registry (search for "Type: variant").
+ *
+ *   <p>However, the variant field in <code>Locale</code> has
+ *   historically been used for any kind of variation, not just
+ *   language variations.  For example, some supported variants
+ *   available in Java SE Runtime Environments indicate alternative
+ *   cultural behaviors such as calendar type or number script.  In
+ *   BCP 47 this kind of information, which does not identify the
+ *   language, is supported by extension subtags or private use
+ *   subtags.</dd><br>
+ *
+ *   <dd>Well-formed variant values have the form <code>SUBTAG
+ *   (('_'|'-') SUBTAG)*</code> where <code>SUBTAG =
+ *   [0-9][0-9a-zA-Z]{3} | [0-9a-zA-Z]{5,8}</code>. (Note: BCP 47 only
+ *   uses hyphen ('-') as a delimiter, this is more lenient).</dd><br>
+ *
+ *   <dd>Example: "polyton" (Polytonic Greek), "POSIX"</dd><br>
+ *
+ *   <dt><a name="def_extensions"/><b>extensions</b></dt>
+ *
+ *   <dd>A map from single character keys to string values, indicating
+ *   extensions apart from language identification.  The extensions in
+ *   <code>Locale</code> implement the semantics and syntax of BCP 47
+ *   extension subtags and private use subtags. The extensions are
+ *   case insensitive, but <code>Locale</code> canonicalizes all
+ *   extension keys and values to lower case. Note that extensions
+ *   cannot have empty values.</dd><br>
+ *
+ *   <dd>Well-formed keys are single characters from the set
+ *   <code>[0-9a-zA-Z]</code>.  Well-formed values have the form
+ *   <code>SUBTAG ('-' SUBTAG)*</code> where for the key 'x'
+ *   <code>SUBTAG = [0-9a-zA-Z]{1,8}</code> and for other keys
+ *   <code>SUBTAG = [0-9a-zA-Z]{2,8}</code> (that is, 'x' allows
+ *   single-character subtags).</dd><br>
+ *
+ *   <dd>Example: key="u"/value="ca-japanese" (Japanese Calendar),
+ *   key="x"/value="java-1-7"</dd>
+ * </dl>
+ *
+ * <b>Note:</b> Although BCP 47 requires field values to be registered
+ * in the IANA Language Subtag Registry, the <code>Locale</code> class
+ * does not provide any validation features.  The <code>Builder</code>
+ * only checks if an individual field satisfies the syntactic
+ * requirement (is well-formed), but does not validate the value
+ * itself.  See {@link Builder} for details.
+ *
+ * <h4><a name="def_locale_extension">Unicode locale/language extension</h4>
+ *
+ * <p>UTS#35, "Unicode Locale Data Markup Language" defines optional
+ * attributes and keywords to override or refine the default behavior
+ * associated with a locale.  A keyword is represented by a pair of
+ * key and type.  For example, "nu-thai" indicates that Thai local
+ * digits (value:"thai") should be used for formatting numbers
+ * (key:"nu").
+ *
+ * <p>The keywords are mapped to a BCP 47 extension value using the
+ * extension key 'u' ({@link #UNICODE_LOCALE_EXTENSION}).  The above
+ * example, "nu-thai", becomes the extension "u-nu-thai".code
+ *
+ * <p>Thus, when a <code>Locale</code> object contains Unicode locale
+ * attributes and keywords,
+ * <code>getExtension(UNICODE_LOCALE_EXTENSION)</code> will return a
+ * String representing this information, for example, "nu-thai".  The
+ * <code>Locale</code> class also provides {@link
+ * #getUnicodeLocaleAttributes}, {@link #getUnicodeLocaleKeys}, and
+ * {@link #getUnicodeLocaleType} which allow you to access Unicode
+ * locale attributes and key/type pairs directly.  When represented as
+ * a string, the Unicode Locale Extension lists attributes
+ * alphabetically, followed by key/type sequences with keys listed
+ * alphabetically (the order of subtags comprising a key's type is
+ * fixed when the type is defined)
+ *
+ * <p>A well-formed locale key has the form
+ * <code>[0-9a-zA-Z]{2}</code>.  A well-formed locale type has the
+ * form <code>"" | [0-9a-zA-Z]{3,8} ('-' [0-9a-zA-Z]{3,8})*</code> (it
+ * can be empty, or a series of subtags 3-8 alphanums in length).  A
+ * well-formed locale attribute has the form
+ * <code>[0-9a-zA-Z]{3,8}</code> (it is a single subtag with the same
+ * form as a locale type subtag).
+ *
+ * <p>The Unicode locale extension specifies optional behavior in
+ * locale-sensitive services.  Although the LDML specification defines
+ * various keys and values, actual locale-sensitive service
+ * implementations in a Java Runtime Environment might not support any
+ * particular Unicode locale attributes or key/type pairs.
+ *
+ * <h4>Creating a Locale</h4>
+ *
+ * <p>There are several different ways to create a <code>Locale</code>
+ * object.
+ *
+ * <h5>Builder</h5>
+ *
+ * <p>Using {@link Builder} you can construct a <code>Locale</code> object
+ * that conforms to BCP 47 syntax.
+ *
+ * <h5>Constructors</h5>
+ *
+ * <p>The <code>Locale</code> class provides three constructors:
  * <blockquote>
  * <pre>
- * Locale(String language)
- * Locale(String language, String country)
- * Locale(String language, String country, String variant)
+ *     {@link #Locale(String language)}
+ *     {@link #Locale(String language, String country)}
+ *     {@link #Locale(String language, String country, String variant)}
  * </pre>
  * </blockquote>
- * The language argument is a valid <STRONG>ISO Language Code.</STRONG>
- * These codes are the lower-case, two-letter codes as defined by ISO-639.
- * You can find a full list of these codes at a number of sites, such as:
- * <BR><a href ="http://www.loc.gov/standards/iso639-2/php/English_list.php">
- * <code>http://www.loc.gov/standards/iso639-2/php/English_list.php</code></a>
+ * These constructors allow you to create a <code>Locale</code> object
+ * with language, country and variant, but you cannot specify
+ * script or extensions.
  *
- * <P>
- * The country argument is a valid <STRONG>ISO Country Code.</STRONG> These
- * codes are the upper-case, two-letter codes as defined by ISO-3166.
- * You can find a full list of these codes at a number of sites, such as:
- * <BR><a href="http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html">
- * <code>http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html</code></a>
+ * <h5>Factory Methods</h5>
  *
- * <P>
- * The variant argument is a vendor or browser-specific code.
- * For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX.
- * Where there are two variants, separate them with an underscore, and
- * put the most important one first. For example, a Traditional Spanish collation
- * might construct a locale with parameters for language, country and variant as:
- * "es", "ES", "Traditional_WIN".
+ * <p>The method {@link #forLanguageTag} creates a <code>Locale</code>
+ * object for a well-formed BCP 47 language tag.
  *
- * <P>
- * Because a <code>Locale</code> object is just an identifier for a region,
- * no validity check is performed when you construct a <code>Locale</code>.
- * If you want to see whether particular resources are available for the
- * <code>Locale</code> you construct, you must query those resources. For
- * example, ask the <code>NumberFormat</code> for the locales it supports
- * using its <code>getAvailableLocales</code> method.
- * <BR><STRONG>Note:</STRONG> When you ask for a resource for a particular
- * locale, you get back the best available match, not necessarily
- * precisely what you asked for. For more information, look at
- * {@link ResourceBundle}.
+ * <h5>Locale Constants</h5>
  *
- * <P>
- * The <code>Locale</code> class provides a number of convenient constants
+ * <p>The <code>Locale</code> class provides a number of convenient constants
  * that you can use to create <code>Locale</code> objects for commonly used
  * locales. For example, the following creates a <code>Locale</code> object
  * for the United States:
  * <blockquote>
  * <pre>
- * Locale.US
+ *     Locale.US
  * </pre>
  * </blockquote>
  *
- * <P>
- * Once you've created a <code>Locale</code> you can query it for information about
- * itself. Use <code>getCountry</code> to get the ISO Country Code and
- * <code>getLanguage</code> to get the ISO Language Code. You can
- * use <code>getDisplayCountry</code> to get the
+ * <h4>Use of Locale</h4>
+ *
+ * <p>Once you've created a <code>Locale</code> you can query it for information
+ * about itself. Use <code>getCountry</code> to get the country (or region)
+ * code and <code>getLanguage</code> to get the language code.
+ * You can use <code>getDisplayCountry</code> to get the
  * name of the country suitable for displaying to the user. Similarly,
  * you can use <code>getDisplayLanguage</code> to get the name of
  * the language suitable for displaying to the user. Interestingly,
@@ -127,28 +281,27 @@
  * and have two versions: one that uses the default locale and one
  * that uses the locale specified as an argument.
  *
- * <P>
- * The Java Platform provides a number of classes that perform locale-sensitive
+ * <p>The Java Platform provides a number of classes that perform locale-sensitive
  * operations. For example, the <code>NumberFormat</code> class formats
- * numbers, currency, or percentages in a locale-sensitive manner. Classes
- * such as <code>NumberFormat</code> have a number of convenience methods
+ * numbers, currency, and percentages in a locale-sensitive manner. Classes
+ * such as <code>NumberFormat</code> have several convenience methods
  * for creating a default object of that type. For example, the
  * <code>NumberFormat</code> class provides these three convenience methods
  * for creating a default <code>NumberFormat</code> object:
  * <blockquote>
  * <pre>
- * NumberFormat.getInstance()
- * NumberFormat.getCurrencyInstance()
- * NumberFormat.getPercentInstance()
+ *     NumberFormat.getInstance()
+ *     NumberFormat.getCurrencyInstance()
+ *     NumberFormat.getPercentInstance()
  * </pre>
  * </blockquote>
- * These methods have two variants; one with an explicit locale
- * and one without; the latter using the default locale.
+ * Each of these methods has two variants; one with an explicit locale
+ * and one without; the latter uses the default locale:
  * <blockquote>
  * <pre>
- * NumberFormat.getInstance(myLocale)
- * NumberFormat.getCurrencyInstance(myLocale)
- * NumberFormat.getPercentInstance(myLocale)
+ *     NumberFormat.getInstance(myLocale)
+ *     NumberFormat.getCurrencyInstance(myLocale)
+ *     NumberFormat.getPercentInstance(myLocale)
  * </pre>
  * </blockquote>
  * A <code>Locale</code> is the mechanism for identifying the kind of object
@@ -156,75 +309,162 @@
  * <STRONG>just</STRONG> a mechanism for identifying objects,
  * <STRONG>not</STRONG> a container for the objects themselves.
  *
- * @see         ResourceBundle
- * @see         java.text.Format
- * @see         java.text.NumberFormat
- * @see         java.text.Collator
- * @author      Mark Davis
- * @since       1.1
+ * <h4>Compatibility</h4>
+ *
+ * <p>In order to maintain compatibility with existing usage, Locale's
+ * constructors retain their behavior prior to the Java Runtime
+ * Environment version 1.7.  The same is largely true for the
+ * <code>toString</code> method. Thus Locale objects can continue to
+ * be used as they were. In particular, clients who parse the output
+ * of toString into language, country, and variant fields can continue
+ * to do so (although this is strongly discouraged), although the
+ * variant field will have additional information in it if script or
+ * extensions are present.
+ *
+ * <p>In addition, BCP 47 imposes syntax restrictions that are not
+ * imposed by Locale's constructors. This means that conversions
+ * between some Locales and BCP 47 language tags cannot be made without
+ * losing information. Thus <code>toLanguageTag</code> cannot
+ * represent the state of locales whose language, country, or variant
+ * do not conform to BCP 47.
+ *
+ * <p>Because of these issues, it is recommended that clients migrate
+ * away from constructing non-conforming locales and use the
+ * <code>forLanguageTag</code> and <code>Locale.Builder</code> APIs instead.
+ * Clients desiring a string representation of the complete locale can
+ * then always rely on <code>toLanguageTag</code> for this purpose.
+ *
+ * <h5><a name="special_cases_constructor"/>Special cases</h5>
+ *
+ * <p>For compatibility reasons, two
+ * non-conforming locales are treated as special cases.  These are
+ * <b><tt>ja_JP_JP</tt></b> and <b><tt>th_TH_TH</tt></b>. These are ill-formed
+ * in BCP 47 since the variants are too short. To ease migration to BCP 47,
+ * these are treated specially during construction.  These two cases (and only
+ * these) cause a constructor to generate an extension, all other values behave
+ * exactly as they did prior to Java 7.
+ *
+ * <p>Java has used <tt>ja_JP_JP</tt> to represent Japanese as used in
+ * Japan together with the Japanese Imperial calendar. This is now
+ * representable using a Unicode locale extension, by specifying the
+ * Unicode locale key <tt>ca</tt> (for "calendar") and type
+ * <tt>japanese</tt>. When the Locale constructor is called with the
+ * arguments "ja", "JP", "JP", the extension "u-ca-japanese" is
+ * automatically added.
+ *
+ * <p>Java has used <tt>th_TH_TH</tt> to represent Thai as used in
+ * Thailand together with Thai digits. This is also now representable using
+ * a Unicode locale extension, by specifying the Unicode locale key
+ * <tt>nu</tt> (for "number") and value <tt>thai</tt>. When the Locale
+ * constructor is called with the arguments "th", "TH", "TH", the
+ * extension "u-nu-thai" is automatically added.
+ *
+ * <h5>Serialization</h5>
+ *
+ * <p>During serialization, writeObject writes all fields to the output
+ * stream, including extensions.
+ *
+ * <p>During deserialization, readResolve adds extensions as described
+ * in <a href="#special_cases_constructor">Special Cases</a>, only
+ * for the two cases th_TH_TH and ja_JP_JP.
+ *
+ * <h5>Legacy language codes</h5>
+ *
+ * <p>Locale's constructor has always converted three language codes to
+ * their earlier, obsoleted forms: <tt>he</tt> maps to <tt>iw</tt>,
+ * <tt>yi</tt> maps to <tt>ji</tt>, and <tt>id</tt> maps to
+ * <tt>in</tt>.  This continues to be the case, in order to not break
+ * backwards compatibility.
+ *
+ * <p>The APIs added in 1.7 map between the old and new language codes,
+ * maintaining the old codes internal to Locale (so that
+ * <code>getLanguage</code> and <code>toString</code> reflect the old
+ * code), but using the new codes in the BCP 47 language tag APIs (so
+ * that <code>toLanguageTag</code> reflects the new one). This
+ * preserves the equivalence between Locales no matter which code or
+ * API is used to construct them. Java's default resource bundle
+ * lookup mechanism also implements this mapping, so that resources
+ * can be named using either convention, see {@link ResourceBundle.Control}.
+ *
+ * <h5>Three-letter language/country(region) codes</h5>
+ *
+ * <p>The Locale constructors have always specified that the language
+ * and the country param be two characters in length, although in
+ * practice they have accepted any length.  The specification has now
+ * been relaxed to allow language codes of two to eight characters and
+ * country (region) codes of two to three characters, and in
+ * particular, three-letter language codes and three-digit region
+ * codes as specified in the IANA Language Subtag Registry.  For
+ * compatibility, the implementation still does not impose a length
+ * constraint.
+ *
+ * @see Builder
+ * @see ResourceBundle
+ * @see java.text.Format
+ * @see java.text.NumberFormat
+ * @see java.text.Collator
+ * @author Mark Davis
+ * @since 1.1
  */
-
 public final class Locale implements Cloneable, Serializable {
 
-    // cache to store singleton Locales
-    private final static ConcurrentHashMap<String, Locale> cache =
-        new ConcurrentHashMap<String, Locale>(32);
+    static private final  Cache LOCALECACHE = new Cache();
 
     /** Useful constant for language.
      */
-    static public final Locale ENGLISH = createSingleton("en__", "en", "");
+    static public final Locale ENGLISH = getInstance("en", "", "");
 
     /** Useful constant for language.
      */
-    static public final Locale FRENCH = createSingleton("fr__", "fr", "");
+    static public final Locale FRENCH = getInstance("fr", "", "");
 
     /** Useful constant for language.
      */
-    static public final Locale GERMAN = createSingleton("de__", "de", "");
+    static public final Locale GERMAN = getInstance("de", "", "");
 
     /** Useful constant for language.
      */
-    static public final Locale ITALIAN = createSingleton("it__", "it", "");
+    static public final Locale ITALIAN = getInstance("it", "", "");
 
     /** Useful constant for language.
      */
-    static public final Locale JAPANESE = createSingleton("ja__", "ja", "");
+    static public final Locale JAPANESE = getInstance("ja", "", "");
 
     /** Useful constant for language.
      */
-    static public final Locale KOREAN = createSingleton("ko__", "ko", "");
+    static public final Locale KOREAN = getInstance("ko", "", "");
 
     /** Useful constant for language.
      */
-    static public final Locale CHINESE = createSingleton("zh__", "zh", "");
+    static public final Locale CHINESE = getInstance("zh", "", "");
 
     /** Useful constant for language.
      */
-    static public final Locale SIMPLIFIED_CHINESE = createSingleton("zh_CN_", "zh", "CN");
+    static public final Locale SIMPLIFIED_CHINESE = getInstance("zh", "CN", "");
 
     /** Useful constant for language.
      */
-    static public final Locale TRADITIONAL_CHINESE = createSingleton("zh_TW_", "zh", "TW");
+    static public final Locale TRADITIONAL_CHINESE = getInstance("zh", "TW", "");
 
     /** Useful constant for country.
      */
-    static public final Locale FRANCE = createSingleton("fr_FR_", "fr", "FR");
+    static public final Locale FRANCE = getInstance("fr", "FR", "");
 
     /** Useful constant for country.
      */
-    static public final Locale GERMANY = createSingleton("de_DE_", "de", "DE");
+    static public final Locale GERMANY = getInstance("de", "DE", "");
 
     /** Useful constant for country.
      */
-    static public final Locale ITALY = createSingleton("it_IT_", "it", "IT");
+    static public final Locale ITALY = getInstance("it", "IT", "");
 
     /** Useful constant for country.
      */
-    static public final Locale JAPAN = createSingleton("ja_JP_", "ja", "JP");
+    static public final Locale JAPAN = getInstance("ja", "JP", "");
 
     /** Useful constant for country.
      */
-    static public final Locale KOREA = createSingleton("ko_KR_", "ko", "KR");
+    static public final Locale KOREA = getInstance("ko", "KR", "");
 
     /** Useful constant for country.
      */
@@ -240,19 +480,19 @@
 
     /** Useful constant for country.
      */
-    static public final Locale UK = createSingleton("en_GB_", "en", "GB");
+    static public final Locale UK = getInstance("en", "GB", "");
 
     /** Useful constant for country.
      */
-    static public final Locale US = createSingleton("en_US_", "en", "US");
+    static public final Locale US = getInstance("en", "US", "");
 
     /** Useful constant for country.
      */
-    static public final Locale CANADA = createSingleton("en_CA_", "en", "CA");
+    static public final Locale CANADA = getInstance("en", "CA", "");
 
     /** Useful constant for country.
      */
-    static public final Locale CANADA_FRENCH = createSingleton("fr_CA_", "fr", "CA");
+    static public final Locale CANADA_FRENCH = getInstance("fr", "CA", "");
 
     /**
      * Useful constant for the root locale.  The root locale is the locale whose
@@ -262,7 +502,25 @@
      *
      * @since 1.6
      */
-    static public final Locale ROOT = createSingleton("__", "", "");
+    static public final Locale ROOT = getInstance("", "", "");
+
+    /**
+     * The key for the private use extension ('x').
+     *
+     * @see #getExtension(char)
+     * @see Builder#setExtension(char, String)
+     * @since 1.7
+     */
+    static public final char PRIVATE_USE_EXTENSION = 'x';
+
+    /**
+     * The key for Unicode locale extension ('u').
+     *
+     * @see #getExtension(char)
+     * @see Builder#setExtension(char, String)
+     * @since 1.7
+     */
+    static public final char UNICODE_LOCALE_EXTENSION = 'u';
 
     /** serialization ID
      */
@@ -274,32 +532,67 @@
     private static final int DISPLAY_LANGUAGE = 0;
     private static final int DISPLAY_COUNTRY  = 1;
     private static final int DISPLAY_VARIANT  = 2;
+    private static final int DISPLAY_SCRIPT = 3;
 
     /**
-     * Construct a locale from language, country, variant.
-     * NOTE:  ISO 639 is not a stable standard; some of the language codes it defines
-     * (specifically iw, ji, and in) have changed.  This constructor accepts both the
-     * old codes (iw, ji, and in) and the new codes (he, yi, and id), but all other
+     * Private constructor used by getInstance method
+     */
+    private Locale(BaseLocale baseLocale, LocaleExtensions extensions) {
+        _baseLocale = baseLocale;
+        _extensions = extensions;
+    }
+
+    /**
+     * Construct a locale from language, country and variant.
+     * This constructor normalizes the language value to lowercase and
+     * the country value to uppercase.
+     * <p>
+     * <b>Note:</b>
+     * <ul>
+     * <li>ISO 639 is not a stable standard; some of the language codes it defines
+     * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
+     * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
      * API on Locale will return only the OLD codes.
-     * @param language lowercase two-letter ISO-639 code.
-     * @param country uppercase two-letter ISO-3166 code.
-     * @param variant vendor and browser specific code. See class description.
+     * <li>For backward compatibility reasons, this constructor does not make
+     * any syntactic checks on the input.
+     * <li>The two cases ("ja", "JP", "JP") and ("th", "TH", "TH") are handled specially,
+     * see <a href="#special_cases_constructor">Special Cases</a> for more information.
+     * </ul>
+     *
+     * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
+     * up to 8 characters in length.  See the <code>Locale</code> class description about
+     * valid language values.
+     * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code.
+     * See the <code>Locale</code> class description about valid country values.
+     * @param variant Any arbitrary value used to indicate a variation of a <code>Locale</code>.
+     * See the <code>Locale</code> class description for the details.
      * @exception NullPointerException thrown if any argument is null.
      */
     public Locale(String language, String country, String variant) {
-        this.language = convertOldISOCodes(language);
-        this.country = toUpperCase(country).intern();
-        this.variant = variant.intern();
+        _baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), "", country, variant);
+        _extensions = getCompatibilityExtensions(language, "", country, variant);
     }
 
     /**
-     * Construct a locale from language, country.
-     * NOTE:  ISO 639 is not a stable standard; some of the language codes it defines
-     * (specifically iw, ji, and in) have changed.  This constructor accepts both the
-     * old codes (iw, ji, and in) and the new codes (he, yi, and id), but all other
+     * Construct a locale from language and country.
+     * This constructor normalizes the language value to lowercase and
+     * the country value to uppercase.
+     * <p>
+     * <b>Note:</b>
+     * <ul>
+     * <li>ISO 639 is not a stable standard; some of the language codes it defines
+     * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
+     * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
      * API on Locale will return only the OLD codes.
-     * @param language lowercase two-letter ISO-639 code.
-     * @param country uppercase two-letter ISO-3166 code.
+     * <li>For backward compatibility reasons, this constructor does not make
+     * any syntactic checks on the input.
+     * </ul>
+     *
+     * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
+     * up to 8 characters in length.  See the <code>Locale</code> class description about
+     * valid language values.
+     * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code.
+     * See the <code>Locale</code> class description about valid country values.
      * @exception NullPointerException thrown if either argument is null.
      */
     public Locale(String language, String country) {
@@ -308,11 +601,21 @@
 
     /**
      * Construct a locale from a language code.
-     * NOTE:  ISO 639 is not a stable standard; some of the language codes it defines
-     * (specifically iw, ji, and in) have changed.  This constructor accepts both the
-     * old codes (iw, ji, and in) and the new codes (he, yi, and id), but all other
+     * This constructor normalizes the language value to lowercase.
+     * <p>
+     * <b>Note:</b>
+     * <ul>
+     * <li>ISO 639 is not a stable standard; some of the language codes it defines
+     * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
+     * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
      * API on Locale will return only the OLD codes.
-     * @param language lowercase two-letter ISO-639 code.
+     * <li>For backward compatibility reasons, this constructor does not make
+     * any syntactic checks on the input.
+     * </ul>
+     *
+     * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
+     * up to 8 characters in length.  See the <code>Locale</code> class description about
+     * valid language values.
      * @exception NullPointerException thrown if argument is null.
      * @since 1.4
      */
@@ -321,32 +624,6 @@
     }
 
     /**
-     * Constructs a <code>Locale</code> using <code>language</code>
-     * and <code>country</code>.  This constructor assumes that
-     * <code>language</code> and <code>contry</code> are interned and
-     * it is invoked by createSingleton only. (flag is just for
-     * avoiding the conflict with the public constructors.
-     */
-    private Locale(String language, String country, boolean flag) {
-        this.language = language;
-        this.country = country;
-        this.variant = "";
-    }
-
-    /**
-     * Creates a <code>Locale</code> instance with the given
-     * <code>language</code> and <code>counry</code> and puts the
-     * instance under the given <code>key</code> in the cache. This
-     * method must be called only when initializing the Locale
-     * constants.
-     */
-    private static Locale createSingleton(String key, String language, String country) {
-        Locale locale = new Locale(language, country, false);
-        cache.put(key, locale);
-        return locale;
-    }
-
-    /**
      * Returns a <code>Locale</code> constructed from the given
      * <code>language</code>, <code>country</code> and
      * <code>variant</code>. If the same <code>Locale</code> instance
@@ -354,29 +631,70 @@
      * returned. Otherwise, a new <code>Locale</code> instance is
      * created and cached.
      *
-     * @param language lowercase two-letter ISO-639 code.
-     * @param country uppercase two-letter ISO-3166 code.
+     * @param language lowercase 2 to 8 language code.
+     * @param country uppercase two-letter ISO-3166 code and numric-3 UN M.49 area code.
      * @param variant vendor and browser specific code. See class description.
      * @return the <code>Locale</code> instance requested
      * @exception NullPointerException if any argument is null.
      */
     static Locale getInstance(String language, String country, String variant) {
-        if (language== null || country == null || variant == null) {
+        return getInstance(language, "", country, variant, LocaleExtensions.EMPTY_EXTENSIONS);
+    }
+
+    static Locale getInstance(String language, String script, String country,
+                                      String variant, LocaleExtensions extensions) {
+        if (language== null || script == null || country == null || variant == null) {
             throw new NullPointerException();
         }
 
-        StringBuilder sb = new StringBuilder();
-        sb.append(language).append('_').append(country).append('_').append(variant);
-        String key = sb.toString();
-        Locale locale = cache.get(key);
-        if (locale == null) {
-            locale = new Locale(language, country, variant);
-            Locale l = cache.putIfAbsent(key, locale);
-            if (l != null) {
-                locale = l;
+        if (extensions == null) {
+            extensions = LocaleExtensions.EMPTY_EXTENSIONS;
+        }
+
+        if (extensions.equals(LocaleExtensions.EMPTY_EXTENSIONS)) {
+            extensions = getCompatibilityExtensions(language, script, country, variant);
+        }
+
+        BaseLocale baseloc = BaseLocale.getInstance(language, script, country, variant);
+        return getInstance(baseloc, extensions);
+    }
+
+    static Locale getInstance(BaseLocale baseloc, LocaleExtensions extensions) {
+        LocaleKey key = new LocaleKey(baseloc, extensions);
+        return LOCALECACHE.get(key);
+    }
+
+    private static class Cache extends LocaleObjectCache<LocaleKey, Locale> {
+        public Cache() {
+        }
+        protected Locale createObject(LocaleKey key) {
+            return new Locale(key._base, key._exts);
+        }
+    }
+
+    private static class LocaleKey {
+        private BaseLocale _base;
+        private LocaleExtensions _exts;
+
+        private LocaleKey(BaseLocale baseLocale, LocaleExtensions extensions) {
+            _base = baseLocale;
+            _exts = extensions;
+        }
+
+        public boolean equals(Object obj) {
+            if (this == obj) {
+                return true;
             }
+            if (!(obj instanceof LocaleKey)) {
+                return false;
+            }
+            LocaleKey other = (LocaleKey)obj;
+            return _base.equals(other._base) && _exts.equals(other._exts);
         }
-        return locale;
+
+        public int hashCode() {
+            return _base.hashCode() ^ _exts.hashCode();
+        }
     }
 
     /**
@@ -395,31 +713,103 @@
         // do not synchronize this method - see 4071298
         // it's OK if more than one default locale happens to be created
         if (defaultLocale == null) {
-            String language, region, country, variant;
+            initDefault();
+        }
+        return defaultLocale;
+    }
+
+    /**
+     * Gets the current value of the default locale for the specified Category
+     * for this instance of the Java Virtual Machine.
+     * <p>
+     * The Java Virtual Machine sets the default locale during startup based
+     * on the host environment. It is used by many locale-sensitive methods
+     * if no locale is explicitly specified. It can be changed using the
+     * setDefault(Locale.Category, Locale) method.
+     *
+     * @param category - the specified category to get the default locale
+     * @throws NullPointerException - if category is null
+     * @return the default locale for the specified Category for this instance
+     *     of the Java Virtual Machine
+     * @see #setDefault(Locale.Category, Locale)
+     * @since 1.7
+     */
+    public static Locale getDefault(Locale.Category category) {
+        // do not synchronize this method - see 4071298
+        // it's OK if more than one default locale happens to be created
+        switch (category) {
+        case DISPLAY:
+            if (defaultDisplayLocale == null) {
+                initDefault(category);
+            }
+            return defaultDisplayLocale;
+        case FORMAT:
+            if (defaultFormatLocale == null) {
+                initDefault(category);
+            }
+            return defaultFormatLocale;
+        default:
+            assert false: "Unknown Category";
+        }
+        return getDefault();
+    }
+
+    private static void initDefault() {
+        String language, region, country, variant;
+        language = AccessController.doPrivileged(
+            new GetPropertyAction("user.language", "en"));
+        // for compatibility, check for old user.region property
+        region = AccessController.doPrivileged(
+            new GetPropertyAction("user.region"));
+        if (region != null) {
+            // region can be of form country, country_variant, or _variant
+            int i = region.indexOf('_');
+            if (i >= 0) {
+                country = region.substring(0, i);
+                variant = region.substring(i + 1);
+            } else {
+                country = region;
+                variant = "";
+            }
+        } else {
+            country = AccessController.doPrivileged(
+                new GetPropertyAction("user.country", ""));
+            variant = AccessController.doPrivileged(
+                new GetPropertyAction("user.variant", ""));
+        }
+        defaultLocale = getInstance(language, country, variant);
+    }
+
+    private static void initDefault(Locale.Category category) {
+        String language, region, country, variant;
+        switch (category) {
+        case DISPLAY:
             language = AccessController.doPrivileged(
-                new GetPropertyAction("user.language", "en"));
-            // for compatibility, check for old user.region property
-            region = AccessController.doPrivileged(
-                new GetPropertyAction("user.region"));
-            if (region != null) {
-                // region can be of form country, country_variant, or _variant
-                int i = region.indexOf('_');
-                if (i >= 0) {
-                    country = region.substring(0, i);
-                    variant = region.substring(i + 1);
-                } else {
-                    country = region;
-                    variant = "";
-                }
+                new GetPropertyAction("user.language.display", ""));
+            if ("".equals(language)) {
+                defaultDisplayLocale = getDefault();
             } else {
                 country = AccessController.doPrivileged(
-                    new GetPropertyAction("user.country", ""));
+                    new GetPropertyAction("user.country.display", ""));
                 variant = AccessController.doPrivileged(
-                    new GetPropertyAction("user.variant", ""));
+                    new GetPropertyAction("user.variant.display", ""));
+                defaultDisplayLocale = getInstance(language, country, variant);
             }
-            defaultLocale = getInstance(language, country, variant);
+            break;
+        case FORMAT:
+            language = AccessController.doPrivileged(
+                new GetPropertyAction("user.language.format", ""));
+            if ("".equals(language)) {
+                defaultFormatLocale = getDefault();
+            } else {
+                country = AccessController.doPrivileged(
+                    new GetPropertyAction("user.country.format", ""));
+                variant = AccessController.doPrivileged(
+                    new GetPropertyAction("user.variant.format", ""));
+                defaultFormatLocale = getInstance(language, country, variant);
+            }
+            break;
         }
-        return defaultLocale;
     }
 
     /**
@@ -438,6 +828,9 @@
      * of functionality, this method should only be used if the caller
      * is prepared to reinitialize locale-sensitive code running
      * within the same Java Virtual Machine.
+     * <p>
+     * By setting the default locale with this method, all of the default
+     * locales for each Category are also set to the specified default locale.
      *
      * @throws SecurityException
      *        if a security manager exists and its
@@ -448,13 +841,59 @@
      * @see java.util.PropertyPermission
      */
     public static synchronized void setDefault(Locale newLocale) {
+        setDefault(Category.DISPLAY, newLocale);
+        setDefault(Category.FORMAT, newLocale);
+        defaultLocale = newLocale;
+    }
+
+    /**
+     * Sets the default locale for the specified Category for this instance
+     * of the Java Virtual Machine. This does not affect the host locale.
+     * <p>
+     * If there is a security manager, its checkPermission method is called
+     * with a PropertyPermission("user.language", "write") permission before
+     * the default locale is changed.
+     * <p>
+     * The Java Virtual Machine sets the default locale during startup based
+     * on the host environment. It is used by many locale-sensitive methods
+     * if no locale is explicitly specified.
+     * <p>
+     * Since changing the default locale may affect many different areas of
+     * functionality, this method should only be used if the caller is
+     * prepared to reinitialize locale-sensitive code running within the
+     * same Java Virtual Machine.
+     * <p>
+     *
+     * @param category - the specified category to set the default locale
+     * @param newLocale - the new default locale
+     * @throws SecurityException - if a security manager exists and its
+     *     checkPermission method doesn't allow the operation.
+     * @throws NullPointerException - if category and/or newLocale is null
+     * @see SecurityManager.checkPermission(java.security.Permission)
+     * @see PropertyPermission
+     * @see #getDefault(Locale.Category)
+     * @since 1.7
+     */
+    public static synchronized void setDefault(Locale.Category category,
+        Locale newLocale) {
+        if (category == null)
+            throw new NullPointerException("Category cannot be NULL");
         if (newLocale == null)
             throw new NullPointerException("Can't set default locale to NULL");
 
         SecurityManager sm = System.getSecurityManager();
         if (sm != null) sm.checkPermission(new PropertyPermission
                         ("user.language", "write"));
-            defaultLocale = newLocale;
+        switch (category) {
+        case DISPLAY:
+            defaultDisplayLocale = newLocale;
+            break;
+        case FORMAT:
+            defaultFormatLocale = newLocale;
+            break;
+        default:
+            assert false: "Unknown Category";
+        }
     }
 
     /**
@@ -474,6 +913,11 @@
     /**
      * Returns a list of all 2-letter country codes defined in ISO 3166.
      * Can be used to create Locales.
+     * <p>
+     * <b>Note:</b> The <code>Locale</code> class also supports other codes for
+     * country (region), such as 3-letter numeric UN M.49 area codes.
+     * Therefore, the list returned by this method does not contain ALL valid
+     * codes that can be used to create Locales.
      */
     public static String[] getISOCountries() {
         if (isoCountries == null) {
@@ -487,9 +931,16 @@
     /**
      * Returns a list of all 2-letter language codes defined in ISO 639.
      * Can be used to create Locales.
-     * [NOTE:  ISO 639 is not a stable standard-- some languages' codes have changed.
+     * <p>
+     * <b>Note:</b>
+     * <ul>
+     * <li>ISO 639 is not a stable standard&mdash; some languages' codes have changed.
      * The list this function returns includes both the new and the old codes for the
-     * languages whose codes have changed.]
+     * languages whose codes have changed.
+     * <li>The <code>Locale</code> class also supports language codes up to
+     * 8 characters in length.  Therefore, the list returned by this method does
+     * not contain ALL valid codes that can be used to create Locales.
+     * </ul>
      */
     public static String[] getISOLanguages() {
         if (isoLanguages == null) {
@@ -510,100 +961,516 @@
     }
 
     /**
-     * Returns the language code for this locale, which will either be the empty string
-     * or a lowercase ISO 639 code.
-     * <p>NOTE:  ISO 639 is not a stable standard-- some languages' codes have changed.
+     * Returns the language code of this Locale.
+     *
+     * <p><b>Note:</b> ISO 639 is not a stable standard&mdash; some languages' codes have changed.
      * Locale's constructor recognizes both the new and the old codes for the languages
      * whose codes have changed, but this function always returns the old code.  If you
-     * want to check for a specific language whose code has changed, don't do <pre>
-     * if (locale.getLanguage().equals("he"))
+     * want to check for a specific language whose code has changed, don't do
+     * <pre>
+     * if (locale.getLanguage().equals("he")) // BAD!
      *    ...
-     * </pre>Instead, do<pre>
-     * if (locale.getLanguage().equals(new Locale("he", "", "").getLanguage()))
-     *    ...</pre>
+     * </pre>
+     * Instead, do
+     * <pre>
+     * if (locale.getLanguage().equals(new Locale("he").getLanguage()))
+     *    ...
+     * </pre>
+     * @return The language code, or the empty string if none is defined.
      * @see #getDisplayLanguage
      */
     public String getLanguage() {
-        return language;
+        return _baseLocale.getLanguage();
     }
 
     /**
-     * Returns the country/region code for this locale, which will
-     * either be the empty string or an uppercase ISO 3166 2-letter code.
+     * Returns the script for this locale, which should
+     * either be the empty string or an ISO 15924 4-letter script
+     * code. The first letter is uppercase and the rest are
+     * lowercase, for example, 'Latn', 'Cyrl'.
+     *
+     * @return The script code, or the empty string if none is defined.
+     * @see #getDisplayScript
+     * @since 1.7
+     */
+    public String getScript() {
+        return _baseLocale.getScript();
+    }
+
+    /**
+     * Returns the country/region code for this locale, which should
+     * either be the empty string, an uppercase ISO 3166 2-letter code,
+     * or a UN M.49 3-digit code.
+     *
+     * @return The country/region code, or the empty string if none is defined.
      * @see #getDisplayCountry
      */
     public String getCountry() {
-        return country;
+        return _baseLocale.getRegion();
     }
 
     /**
      * Returns the variant code for this locale.
+     *
+     * @return The variant code, or the empty string if none is defined.
      * @see #getDisplayVariant
      */
     public String getVariant() {
-        return variant;
+        return _baseLocale.getVariant();
     }
 
     /**
-     * Getter for the programmatic name of the entire locale,
-     * with the language, country and variant separated by underbars.
-     * Language is always lower case, and country is always upper case.
-     * If the language is missing, the string will begin with an underbar.
-     * If both the language and country fields are missing, this function
-     * will return the empty string, even if the variant field is filled in
-     * (you can't have a locale with just a variant-- the variant must accompany
-     * a valid language or country code).
-     * Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC"
+     * Returns the extension (or private use) value associated with
+     * the specified key, or null if there is no extension
+     * associated with the key. To be well-formed, the key must be one
+     * of <code>[0-9A-Za-z]</code>. Keys are case-insensitive, so
+     * for example 'z' and 'Z' represent the same extension.
+     *
+     * @param key the extension key
+     * @return The extension, or null if this locale defines no
+     * extension for the specified key.
+     * @throws IllegalArgumentException if key is not well-formed
+     * @see #PRIVATE_USE_EXTENSION
+     * @see #UNICODE_LOCALE_EXTENSION
+     * @since 1.7
+     */
+    public String getExtension(char key) {
+        if (!LocaleExtensions.isValidKey(key)) {
+            throw new IllegalArgumentException("Ill-formed extension key: " + key);
+        }
+        return _extensions.getExtensionValue(key);
+    }
+
+    /**
+     * Returns the set of extension keys associated with this locale, or the
+     * empty set if it has no extensions. The returned set is unmodifiable.
+     * The keys will all be lower-case.
+     *
+     * @return The set of extension keys, or the empty set if this locale has
+     * no extensions.
+     * @since 1.7
+     */
+    public Set<Character> getExtensionKeys() {
+        return _extensions.getKeys();
+    }
+
+    /**
+     * Returns the set of unicode locale attributes associated with
+     * this locale, or the empty set if it has no attributes. The
+     * returned set is unmodifiable.
+     *
+     * @return The set of attributes.
+     * @since 1.7
+     */
+    public Set<String> getUnicodeLocaleAttributes() {
+        return _extensions.getUnicodeLocaleAttributes();
+    }
+
+    /**
+     * Returns the Unicode locale type associated with the specified Unicode locale key
+     * for this locale. Returns the empty string for keys that are defined with no type.
+     * Returns null if the key is not defined. Keys are case-insensitive. The key must
+     * be two alphanumeric characters ([0-9a-zA-Z]), or an IllegalArgumentException is
+     * thrown.
+     *
+     * @param key the Unicode locale key
+     * @return The Unicode locale type associated with the key, or null if the
+     * locale does not define the key.
+     * @throws IllegalArgumentException if the key is not well-formed
+     * @throws NullPointerException if <code>key</code> is null
+     * @since 1.7
+     */
+    public String getUnicodeLocaleType(String key) {
+        if (!UnicodeLocaleExtension.isKey(key)) {
+            throw new IllegalArgumentException("Ill-formed Unicode locale key: " + key);
+        }
+        return _extensions.getUnicodeLocaleType(key);
+    }
+
+    /**
+     * Returns the set of Unicode locale keys defined by this locale, or the empty set if
+     * this locale has none.  The returned set is immutable.  Keys are all lower case.
+     *
+     * @return The set of Unicode locale keys, or the empty set if this locale has
+     * no Unicode locale keywords.
+     * @since 1.7
+     */
+    public Set<String> getUnicodeLocaleKeys() {
+        return _extensions.getUnicodeLocaleKeys();
+    }
+
+    /**
+     * Package locale method returning the Locale's BaseLocale,
+     * used by ResourceBundle
+     * @return base locale of this Locale
+     */
+    BaseLocale getBaseLocale() {
+        return _baseLocale;
+    }
+
+    /**
+     * Package local method returning the Locale's LocaleExtensions,
+     * used by ResourceBundle
+     * @return locale exnteions of this Locale
+     */
+     LocaleExtensions getLocaleExtensions() {
+         return _extensions;
+     }
+
+    /**
+     * Returns a string representation of this <code>Locale</code>
+     * object, consisting of language, country, variant, script,
+     * and extensions as below:
+     * <p><blockquote>
+     * language + "_" + country + "_" + (variant + "_#" | "#") + script + "-" + extensions
+     * </blockquote>
+     *
+     * Language is always lower case, country is always upper case, script is always title
+     * case, and extensions are always lower case.  Extensions and private use subtags
+     * will be in canonical order as explained in {@link #toLanguageTag}.
+     *
+     * <p>When the locale has neither script nor extensions, the result is the same as in
+     * Java 6 and prior.
+     *
+     * <p>If both the language and country fields are missing, this function will return
+     * the empty string, even if the variant, script, or extensions field is present (you
+     * can't have a locale with just a variant, the variant must accompany a well-formed
+     * language or country code).
+     *
+     * <p>If script or extensions are present and variant is missing, no underscore is
+     * added before the "#".
+     *
+     * <p>This behavior is designed to support debugging and to be compatible with
+     * previous uses of <code>toString</code> that expected language, country, and variant
+     * fields only.  To represent a Locale as a String for interchange purposes, use
+     * {@link #toLanguageTag}.
+     *
+     * <p>Examples: <ul><tt>
+     * <li>en
+     * <li>de_DE
+     * <li>_GB
+     * <li>en_US_WIN
+     * <li>de__POSIX
+     * <li>zh_CN_#Hans
+     * <li>zh_TW_#Hant-x-java
+     * <li>th_TH_TH_#u-nu-thai</tt></ul>
+     *
+     * @return A string representation of the Locale, for debugging.
      * @see #getDisplayName
+     * @see #toLanguageTag
      */
     public final String toString() {
-        boolean l = language.length() != 0;
-        boolean c = country.length() != 0;
-        boolean v = variant.length() != 0;
-        StringBuilder result = new StringBuilder(language);
-        if (c||(l&&v)) {
-            result.append('_').append(country); // This may just append '_'
+        boolean l = (_baseLocale.getLanguage().length() != 0);
+        boolean s = (_baseLocale.getScript().length() != 0);
+        boolean r = (_baseLocale.getRegion().length() != 0);
+        boolean v = (_baseLocale.getVariant().length() != 0);
+        boolean e = (_extensions.getID().length() != 0);
+
+        StringBuilder result = new StringBuilder(_baseLocale.getLanguage());
+        if (r || (l && v)) {
+            result.append('_')
+                .append(_baseLocale.getRegion()); // This may just append '_'
         }
-        if (v&&(l||c)) {
-            result.append('_').append(variant);
+        if (v && (l || r)) {
+            result.append('_')
+                .append(_baseLocale.getVariant());
         }
+
+        if (s && (l || r)) {
+            result.append("_#")
+                .append(_baseLocale.getScript());
+        }
+
+        if (e && (l || r)) {
+            result.append('_');
+            if (!s) {
+                result.append('#');
+            }
+            result.append(_extensions.getID());
+        }
+
         return result.toString();
     }
 
     /**
-     * Returns a three-letter abbreviation for this locale's language.  If the locale
-     * doesn't specify a language, this will be the empty string.  Otherwise, this will
-     * be a lowercase ISO 639-2/T language code.
-     * The ISO 639-2 language codes can be found on-line at
-     * <a href="http://www.loc.gov/standards/iso639-2/englangn.html">
-     * <code>http://www.loc.gov/standards/iso639-2/englangn.html</code>.</a>
-     * @exception MissingResourceException Throws MissingResourceException if the
+     * Returns a well-formed IETF BCP 47 language tag representing
+     * this locale.
+     *
+     * <p>If this <code>Locale</code> has a language, country, or
+     * variant that does not satisfy the IETF BCP 47 language tag
+     * syntax requirements, this method handles these fields as
+     * described below:
+     *
+     * <p><b>Language:</b> If language is empty, or not <a
+     * href="#def_language" >well-formed</a> (for example "a" or
+     * "e2"), it will be emitted as "und" (Undetermined).
+     *
+     * <p><b>Country:</b> If country is not <a
+     * href="#def_region">well-formed</a> (for example "12" or "USA"),
+     * it will be omitted.
+     *
+     * <p><b>Variant:</b> If variant <b>is</b> <a
+     * href="#def_variant">well-formed</a>, each sub-segment
+     * (delimited by '-' or '_') is emitted as a subtag.  Otherwise:
+     * <ul>
+     *
+     * <li>if all sub-segments match <code>[0-9a-zA-Z]{1,8}</code>
+     * (for example "WIN" or "Oracle_JDK_Standard_Edition"), the first
+     * ill-formed sub-segment and all following will be appended to
+     * the private use subtag.  The first appended subtag will be
+     * "lvariant", followed by the sub-segments in order, separated by
+     * hyphen. For example, "x-lvariant-WIN",
+     * "Oracle-x-lvariant-JDK-Standard-Edition".
+     *
+     * <li>if any sub-segment does not match
+     * <code>[0-9a-zA-Z]{1,8}</code>, the variant will be truncated
+     * and the problematic sub-segment and all following sub-segments
+     * will be omitted.  If the remainder is non-empty, it will be
+     * emitted as a private use subtag as above (even if the remainder
+     * turns out to be well-formed).  For example,
+     * "Solaris_isjustthecoolestthing" is emitted as
+     * "x-lvariant-Solaris", not as "solaris".</li></ul>
+     *
+     * <p><b>Compatibility special cases:</b><ul>
+     *
+     * <li>The language codes "iw", "ji", and "in" are handled
+     * specially. Java uses these deprecated codes for compatibility
+     * reasons. The <code>toLanguageTag</code> method converts these
+     * three codes (and only these three) to "he", "yi", and "id"
+     * respectively.
+     *
+     * <li>A locale with language "no", country "NO", and variant
+     * "NY", representing Norwegian Nynorsk, will be represented as
+     * having language "nn", country "NO", and empty variant. This is
+     * because some JVMs used the deprecated form to represent the
+     * user's default locale, and for compatibility reasons that Take a has
+     * not been changed.</ul>
+     *
+     * <p><b>Note:</b> Although the language tag created by this
+     * method is well-formed (satisfies the syntax requirements
+     * defined by the IETF BCP 47 specification), it is not
+     * necessarily a valid BCP 47 language tag.  For example,
+     * <pre>
+     *   new Locale("xx", "YY").toLanguageTag();</pre>
+     *
+     * will return "xx-YY", but the language subtag "xx" and the
+     * region subtag "YY" are invalid because they are not registered
+     * in the IANA Language Subtag Registry.
+     *
+     * @return a BCP47 language tag representing the locale
+     * @see #forLanguageTag(String)
+     * @since 1.7
+     */
+    public String toLanguageTag() {
+        LanguageTag tag = LanguageTag.parseLocale(_baseLocale, _extensions);
+        StringBuilder buf = new StringBuilder();
+
+        String subtag = tag.getLanguage();
+        buf.append(LanguageTag.canonicalizeLanguage(subtag));
+
+        subtag = tag.getScript();
+        if (subtag.length() > 0) {
+            buf.append(LanguageTag.SEP);
+            buf.append(LanguageTag.canonicalizeScript(subtag));
+        }
+
+        subtag = tag.getRegion();
+        if (subtag.length() > 0) {
+            buf.append(LanguageTag.SEP);
+            buf.append(LanguageTag.canonicalizeRegion(subtag));
+        }
+
+        List<String>subtags = tag.getVariants();
+        for (String s : subtags) {
+            buf.append(LanguageTag.SEP);
+            // preserve casing
+            buf.append(s);
+        }
+
+        subtags = tag.getExtensions();
+        for (String s : subtags) {
+            buf.append(LanguageTag.SEP);
+            buf.append(LanguageTag.canonicalizeExtension(s));
+        }
+
+        subtag = tag.getPrivateuse();
+        if (subtag.length() > 0) {
+            buf.append(LanguageTag.SEP).append(LanguageTag.PRIVATEUSE).append(LanguageTag.SEP);
+            // preserve casing
+            buf.append(subtag);
+        }
+
+        return buf.toString();
+    }
+
+    /**
+     * Returns a locale for the specified IETF BCP 47 language tag string.
+     *
+     * <p>If the specified language tag contains any ill-formed subtags,
+     * the first such subtag and all following subtags are ignored.  Compare
+     * to {@link Locale.Builder#setLanguageTag} which throws an exception
+     * in this case.
+     *
+     * <p>The following <b>conversions</b> are performed:<ul>
+     *
+     * <li>The language code "und" is mapped to language "".
+     *
+     * <li>The language codes "he", "yi", and "id" are mapped to "iw",
+     * "ji", and "in" respectively. (This is the same canonicalization
+     * that's done in Locale's constructors.)
+     *
+     * <li>The portion of a private use subtag prefixed by "lvariant",
+     * if any, is removed and appended to the variant field in the
+     * result locale (without case normalization).  If it is then
+     * empty, the private use subtag is discarded:
+     *
+     * <pre>
+     *     Locale loc;
+     *     loc = Locale.forLanguageTag("en-US-x-lvariant-POSIX);
+     *     loc.getVariant(); // returns "POSIX"
+     *     loc.getExtension('x'); // returns null
+     *
+     *     loc = Locale.forLanguageTag("de-POSIX-x-URP-lvariant-Abc-Def");
+     *     loc.getVariant(); // returns "POSIX_Abc_Def"
+     *     loc.getExtension('x'); // returns "urp"
+     * </pre>
+     *
+     * <li>When the languageTag argument contains an extlang subtag,
+     * the first such subtag is used as the language, and the primary
+     * language subtag and other extlang subtags are ignored:
+     *
+     * <pre>
+     *     Locale.forLanguageTag("ar-aao").getLanguage(); // returns "aao"
+     *     Locale.forLanguageTag("en-abc-def-us").toString(); // returns "abc_US"
+     * </pre>
+     *
+     * <li>Case is normalized except for variant tags, which are left
+     * unchanged.  Language is normalized to lower case, script to
+     * title case, country to upper case, and extensions to lower
+     * case.
+     *
+     * <li>If, after processing, the locale would exactly match either
+     * ja_JP_JP or th_TH_TH with no extensions, the appropriate
+     * extensions are added as though the constructor had been called:
+     *
+     * <pre>
+     *    Locale.forLanguageTag("ja-JP-x-lvariant-JP).toLanguageTag();
+     *    // returns ja-JP-u-ca-japanese-x-lvariant-JP
+     *    Locale.forLanguageTag("th-TH-x-lvariant-TH).toLanguageTag();
+     *    // returns th-TH-u-nu-thai-x-lvariant-TH
+     * <pre></ul>
+     *
+     * <p>This implements the 'Language-Tag' production of BCP47, and
+     * so supports grandfathered (regular and irregular) as well as
+     * private use language tags.  Stand alone private use tags are
+     * represented as empty language and extension 'x-whatever',
+     * and grandfathered tags are converted to their canonical replacements
+     * where they exist.
+     *
+     * <p>Grandfathered tags with canonical replacements are as follows:
+     *
+     * <table>
+     * <tbody align="center">
+     * <tr><th>grandfathered tag</th><th>&nbsp;</th><th>modern replacement</th></tr>
+     * <tr><td>art-lojban</td><td>&nbsp;</td><td>jbo</td></tr>
+     * <tr><td>i-ami</td><td>&nbsp;</td><td>ami</td></tr>
+     * <tr><td>i-bnn</td><td>&nbsp;</td><td>bnn</td></tr>
+     * <tr><td>i-hak</td><td>&nbsp;</td><td>hak</td></tr>
+     * <tr><td>i-klingon</td><td>&nbsp;</td><td>tlh</td></tr>
+     * <tr><td>i-lux</td><td>&nbsp;</td><td>lb</td></tr>
+     * <tr><td>i-navajo</td><td>&nbsp;</td><td>nv</td></tr>
+     * <tr><td>i-pwn</td><td>&nbsp;</td><td>pwn</td></tr>
+     * <tr><td>i-tao</td><td>&nbsp;</td><td>tao</td></tr>
+     * <tr><td>i-tay</td><td>&nbsp;</td><td>tay</td></tr>
+     * <tr><td>i-tsu</td><td>&nbsp;</td><td>tsu</td></tr>
+     * <tr><td>no-bok</td><td>&nbsp;</td><td>nb</td></tr>
+     * <tr><td>no-nyn</td><td>&nbsp;</td><td>nn</td></tr>
+     * <tr><td>sgn-BE-FR</td><td>&nbsp;</td><td>sfb</td></tr>
+     * <tr><td>sgn-BE-NL</td><td>&nbsp;</td><td>vgt</td></tr>
+     * <tr><td>sgn-CH-DE</td><td>&nbsp;</td><td>sgg</td></tr>
+     * <tr><td>zh-guoyu</td><td>&nbsp;</td><td>cmn</td></tr>
+     * <tr><td>zh-hakka</td><td>&nbsp;</td><td>hak</td></tr>
+     * <tr><td>zh-min-nan</td><td>&nbsp;</td><td>nan</td></tr>
+     * <tr><td>zh-xiang</td><td>&nbsp;</td><td>hsn</td></tr>
+     * </tbody>
+     * </table>
+     *
+     * <p>Grandfathered tags with no modern replacement will be
+     * converted as follows:
+     *
+     * <table>
+     * <tbody align="center">
+     * <tr><th>grandfathered tag</th><th>&nbsp;</th><th>converts to</th></tr>
+     * <tr><td>cel-gaulish</td><td>&nbsp;</td><td>xtg-x-cel-gaulish</td></tr>
+     * <tr><td>en-GB-oed</td><td>&nbsp;</td><td>en-GB-x-oed</td></tr>
+     * <tr><td>i-default</td><td>&nbsp;</td><td>en-x-i-default</td></tr>
+     * <tr><td>i-enochian</td><td>&nbsp;</td><td>und-x-i-enochian</td></tr>
+     * <tr><td>i-mingo</td><td>&nbsp;</td><td>see-x-i-mingo</td></tr>
+     * <tr><td>zh-min</td><td>&nbsp;</td><td>nan-x-zh-min</td></tr>
+     * </tbody>
+     * </table>
+     *
+     * <p>For a list of all grandfathered tags, see the
+     * IANA Language Subtag Registry (search for "Type: grandfathered").
+     *
+     * <p><b>Note</b>: there is no guarantee that <code>toLanguageTag</code>
+     * and <code>forLanguageTag</code> will round-trip.
+     *
+     * @param languageTag the language tag
+     * @return The locale that best represents the language tag.
+     * @throws NullPointerException if <code>languageTag</code> is <code>null</code>
+     * @see #toLanguageTag()
+     * @see java.util.Locale.Builder#setLanguageTag(String)
+     * @since 1.7
+     */
+    public static Locale forLanguageTag(String languageTag) {
+        LanguageTag tag = LanguageTag.parse(languageTag, null);
+        InternalLocaleBuilder bldr = new InternalLocaleBuilder();
+        bldr.setLanguageTag(tag);
+        return getInstance(bldr.getBaseLocale(), bldr.getLocaleExtensions());
+    }
+
+    /**
+     * Returns a three-letter abbreviation of this locale's language.
+     * If the language matches an ISO 639-1 two-letter code, the
+     * corresponding ISO 639-2/T three-letter lowercase code is
+     * returned.  The ISO 639-2 language codes can be found on-line,
+     * see "Codes for the Representation of Names of Languages Part 2:
+     * Alpha-3 Code".  If the locale specifies a three-letter
+     * language, the language is returned as is.  If the locale does
+     * not specify a language the empty string is returned.
+     *
+     * @return A three-letter abbreviation of this locale's language.
+     * @exception MissingResourceException Throws MissingResourceException if
      * three-letter language abbreviation is not available for this locale.
      */
     public String getISO3Language() throws MissingResourceException {
-        String language3 = getISO3Code(language, LocaleISOData.isoLanguageTable);
+        String language3 = getISO3Code(_baseLocale.getLanguage(), LocaleISOData.isoLanguageTable);
         if (language3 == null) {
             throw new MissingResourceException("Couldn't find 3-letter language code for "
-                    + language, "FormatData_" + toString(), "ShortLanguage");
+                    + _baseLocale.getLanguage(), "FormatData_" + toString(), "ShortLanguage");
         }
         return language3;
     }
 
     /**
-     * Returns a three-letter abbreviation for this locale's country.  If the locale
-     * doesn't specify a country, this will be the empty string.  Otherwise, this will
-     * be an uppercase ISO 3166 3-letter country code.
-     * The ISO 3166-2 country codes can be found on-line at
-     * <a href="http://www.davros.org/misc/iso3166.txt">
-     * <code>http://www.davros.org/misc/iso3166.txt</code>.</a>
+     * Returns a three-letter abbreviation for this locale's country.
+     * If the country matches an ISO 3166-1 alpha-2 code, the
+     * corresponding ISO 3166-1 alpha-3 uppercase code is returned.
+     * If the locale doesn't specify a country, this will be the empty
+     * string.
+     *
+     * <p>The ISO 3166-1 codes can be found on-line.
+     *
+     * @return A three-letter abbreviation of this locale's country.
      * @exception MissingResourceException Throws MissingResourceException if the
      * three-letter country abbreviation is not available for this locale.
      */
     public String getISO3Country() throws MissingResourceException {
-        String country3 = getISO3Code(country, LocaleISOData.isoCountryTable);
+        String country3 = getISO3Code(_baseLocale.getRegion(), LocaleISOData.isoCountryTable);
         if (country3 == null) {
             throw new MissingResourceException("Couldn't find 3-letter country code for "
-                    + country, "FormatData_" + toString(), "ShortCountry");
+                    + _baseLocale.getRegion(), "FormatData_" + toString(), "ShortCountry");
         }
         return country3;
     }
@@ -642,7 +1509,7 @@
      * value.  If the locale doesn't specify a language, this function returns the empty string.
      */
     public final String getDisplayLanguage() {
-        return getDisplayLanguage(getDefault());
+        return getDisplayLanguage(getDefault(Category.DISPLAY));
     }
 
     /**
@@ -661,7 +1528,33 @@
      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
      */
     public String getDisplayLanguage(Locale inLocale) {
-        return getDisplayString(language, inLocale, DISPLAY_LANGUAGE);
+        return getDisplayString(_baseLocale.getLanguage(), inLocale, DISPLAY_LANGUAGE);
+    }
+
+    /**
+     * Returns a name for the the locale's script that is appropriate for display to
+     * the user. If possible, the name will be localized for the default locale.  Returns
+     * the empty string if this locale doesn't specify a script code.
+     *
+     * @return the display name of the script code for the current default locale
+     * @since 1.7
+     */
+    public String getDisplayScript() {
+        return getDisplayScript(getDefault());
+    }
+
+    /**
+     * Returns a name for the locale's script that is appropriate
+     * for display to the user. If possible, the name will be
+     * localized for the given locale. Returns the empty string if
+     * this locale doesn't specify a script code.
+     *
+     * @return the display name of the script code for the current default locale
+     * @throws NullPointerException if <code>inLocale</code> is <code>null</code>
+     * @since 1.7
+     */
+    public String getDisplayScript(Locale inLocale) {
+        return getDisplayString(_baseLocale.getScript(), inLocale, DISPLAY_SCRIPT);
     }
 
     /**
@@ -677,7 +1570,7 @@
      * value.  If the locale doesn't specify a country, this function returns the empty string.
      */
     public final String getDisplayCountry() {
-        return getDisplayCountry(getDefault());
+        return getDisplayCountry(getDefault(Category.DISPLAY));
     }
 
     /**
@@ -696,7 +1589,7 @@
      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
      */
     public String getDisplayCountry(Locale inLocale) {
-        return getDisplayString(country, inLocale, DISPLAY_COUNTRY);
+        return getDisplayString(_baseLocale.getRegion(), inLocale, DISPLAY_COUNTRY);
     }
 
     private String getDisplayString(String code, Locale inLocale, int type) {
@@ -744,7 +1637,7 @@
      * doesn't specify a variant code, this function returns the empty string.
      */
     public final String getDisplayVariant() {
-        return getDisplayVariant(getDefault());
+        return getDisplayVariant(getDefault(Category.DISPLAY));
     }
 
     /**
@@ -755,7 +1648,7 @@
      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
      */
     public String getDisplayVariant(Locale inLocale) {
-        if (variant.length() == 0)
+        if (_baseLocale.getVariant().length() == 0)
             return "";
 
         OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale);
@@ -776,39 +1669,44 @@
 
     /**
      * Returns a name for the locale that is appropriate for display to the
-     * user.  This will be the values returned by getDisplayLanguage(), getDisplayCountry(),
-     * and getDisplayVariant() assembled into a single string.  The display name will have
-     * one of the following forms:<p><blockquote>
-     * language (country, variant)<p>
-     * language (country)<p>
-     * language (variant)<p>
-     * country (variant)<p>
-     * language<p>
-     * country<p>
-     * variant<p></blockquote>
-     * depending on which fields are specified in the locale.  If the language, country,
-     * and variant fields are all empty, this function returns the empty string.
+     * user. This will be the values returned by getDisplayLanguage(),
+     * getDisplayScript(), getDisplayCountry(), and getDisplayVariant() assembled
+     * into a single string. The the non-empty values are used in order,
+     * with the second and subsequent names in parentheses.  For example:
+     * <blockquote>
+     * language (script, country, variant)<br>
+     * language (country)<br>
+     * language (variant)<br>
+     * script (country)<br>
+     * country<br>
+     * </blockquote>
+     * depending on which fields are specified in the locale.  If the
+     * language, sacript, country, and variant fields are all empty,
+     * this function returns the empty string.
      */
     public final String getDisplayName() {
-        return getDisplayName(getDefault());
+        return getDisplayName(getDefault(Category.DISPLAY));
     }
 
     /**
-     * Returns a name for the locale that is appropriate for display to the
-     * user.  This will be the values returned by getDisplayLanguage(), getDisplayCountry(),
-     * and getDisplayVariant() assembled into a single string.  The display name will have
-     * one of the following forms:<p><blockquote>
-     * language (country, variant)<p>
-     * language (country)<p>
-     * language (variant)<p>
-     * country (variant)<p>
-     * language<p>
-     * country<p>
-     * variant<p></blockquote>
-     * depending on which fields are specified in the locale.  If the language, country,
-     * and variant fields are all empty, this function returns the empty string.
+     * Returns a name for the locale that is appropriate for display
+     * to the user.  This will be the values returned by
+     * getDisplayLanguage(), getDisplayScript(),getDisplayCountry(),
+     * and getDisplayVariant() assembled into a single string.
+     * The non-empty values are used in order,
+     * with the second and subsequent names in parentheses.  For example:
+     * <blockquote>
+     * language (script, country, variant)<br>
+     * language (country)<br>
+     * language (variant)<br>
+     * script (country)<br>
+     * country<br>
+     * </blockquote>
+     * depending on which fields are specified in the locale.  If the
+     * language, script, country, and variant fields are all empty,
+     * this function returns the empty string.
      *
-     * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
+     * @throws NullPointerException if <code>inLocale</code> is <code>null</code>
      */
     public String getDisplayName(Locale inLocale) {
         OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale);
@@ -888,7 +1786,7 @@
     }
 
     /**
-     * Overrides Cloneable
+     * Overrides Cloneable.
      */
     public Object clone()
     {
@@ -908,7 +1806,7 @@
     public int hashCode() {
         int hc = hashCodeValue;
         if (hc == 0) {
-            hc = (language.hashCode() << 8) ^ country.hashCode() ^ (variant.hashCode() << 4);
+            hc = _baseLocale.hashCode() ^ _extensions.hashCode();
             hashCodeValue = hc;
         }
         return hc;
@@ -918,8 +1816,8 @@
 
     /**
      * Returns true if this Locale is equal to another object.  A Locale is
-     * deemed equal to another Locale with identical language, country,
-     * and variant, and unequal to all other objects.
+     * deemed equal to another Locale with identical language, script, country,
+     * variant and extensions, and unequal to all other objects.
      *
      * @return true if this Locale is equal to the specified object.
      */
@@ -929,47 +1827,24 @@
             return true;
         if (!(obj instanceof Locale))
             return false;
-        Locale other = (Locale) obj;
-        return language == other.language
-            && country == other.country
-            && variant == other.variant;
+        BaseLocale otherBase = ((Locale)obj)._baseLocale;
+        LocaleExtensions otherExt = ((Locale)obj)._extensions;
+        return _baseLocale.equals(otherBase) && _extensions.equals(otherExt);
     }
 
     // ================= privates =====================================
 
-    // XXX instance and class variables. For now keep these separate, since it is
-    // faster to match. Later, make into single string.
+    private transient BaseLocale _baseLocale;
+    private transient LocaleExtensions _extensions;
 
     /**
-     * @serial
-     * @see #getLanguage
-     */
-    private final String language;
-
-    /**
-     * @serial
-     * @see #getCountry
-     */
-    private final String country;
-
-    /**
-     * @serial
-     * @see #getVariant
-     */
-    private final String variant;
-
-    /**
-     * Placeholder for the object's hash code.  Always -1.
-     * @serial
-     */
-    private volatile int hashcode = -1;        // lazy evaluate
-
-    /**
-     * Calculated hashcode to fix 4518797.
+     * Calculated hashcode
      */
     private transient volatile int hashCodeValue = 0;
 
     private static Locale defaultLocale = null;
+    private static Locale defaultDisplayLocale = null;
+    private static Locale defaultFormatLocale = null;
 
     /**
      * Return an array of the display names of the variant.
@@ -978,7 +1853,7 @@
      */
     private String[] getDisplayVariantArray(OpenListResourceBundle bundle, Locale inLocale) {
         // Split the variant name into tokens separated by '_'.
-        StringTokenizer tokenizer = new StringTokenizer(variant, "_");
+        StringTokenizer tokenizer = new StringTokenizer(_baseLocale.getVariant(), "_");
         String[] names = new String[tokenizer.countTokens()];
 
         // For each variant token, lookup the display name.  If
@@ -1056,49 +1931,102 @@
     }
 
     /**
-     * Replace the deserialized Locale object with a newly
-     * created object. Newer language codes are replaced with older ISO
-     * codes. The country and variant codes are replaced with internalized
-     * String copies.
+     * @serialField language    String
+     *      language subtag in lower case. (See <a href="java/util/Locale.html#getLanguage()">getLanguage()</a>)
+     * @serialField country     String
+     *      country subtag in upper case. (See <a href="java/util/Locale.html#getCountry()">getCountry()</a>)
+     * @serialField variant     String
+     *      variant subtags separated by LOWLINE characters. (See <a href="java/util/Locale.html#getVariant()">getVariant()</a>)
+     * @serialField hashcode    int
+     *      deprectated, for forward compatibility only
+     * @serialField script      String
+     *      script subtag in title case (See <a href="java/util/Locale.html#getScript()">getScript()</a>)
+     * @serialField extensions  String
+     *      canonical representation of extensions, that is,
+     *      BCP47 extensions in alphabetical order followed by
+     *      BCP47 private use subtags, all in lower case letters
+     *      separated by HYPHEN-MINUS characters.
+     *      (See <a href="java/util/Locale.html#getExtensionKeys()">getExtensionKeys()</a>,
+     *      <a href="java/util/Locale.html#getExtension(char)">getExtension(char)</a>)
+     */
+    private static final ObjectStreamField[] serialPersistentFields = {
+        new ObjectStreamField("language", String.class),
+        new ObjectStreamField("country", String.class),
+        new ObjectStreamField("variant", String.class),
+        new ObjectStreamField("hashcode", int.class),
+        new ObjectStreamField("script", String.class),
+        new ObjectStreamField("extensions", String.class),
+    };
+
+    /**
+     * Serializes this <code>Locale</code> to the specified <code>ObjectOutputStream</code>.
+     * @param out the <code>ObjectOutputStream</code> to write
+     * @throws IOException
+     * @since 1.7
+     */
+    private void writeObject(ObjectOutputStream out) throws IOException {
+        ObjectOutputStream.PutField fields = out.putFields();
+        fields.put("language", _baseLocale.getLanguage());
+        fields.put("script", _baseLocale.getScript());
+        fields.put("country", _baseLocale.getRegion());
+        fields.put("variant", _baseLocale.getVariant());
+        fields.put("extensions", _extensions.getID());
+        fields.put("hashcode", -1); // place holder just for backward support
+        out.writeFields();
+    }
+
+    /**
+     * Deserialize this <code>Locale</code>.
+     * @param in the <code>ObjectInputStream</code> to read
+     * @throws IOException
+     * @throws ClassNotFoundException
+     * @throws IllformdLocaleException
+     * @since 1.7
+     */
+    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
+        ObjectInputStream.GetField fields = in.readFields();
+        String language = (String)fields.get("language", "");
+        String script = (String)fields.get("script", "");
+        String country = (String)fields.get("country", "");
+        String variant = (String)fields.get("variant", "");
+        String extStr = (String)fields.get("extensions", "");
+        _baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), script, country, variant);
+        try {
+            InternalLocaleBuilder bldr = new InternalLocaleBuilder();
+            bldr.setExtensions(extStr);
+            _extensions = bldr.getLocaleExtensions();
+        } catch (LocaleSyntaxException e) {
+            throw new IllformedLocaleException(e.getMessage());
+        }
+    }
+
+    /**
+     * Returns a cached <code>Locale</code> instance equivalent to
+     * the deserialized <code>Locale</code>. When serialized
+     * language, country and variant fields read from the object data stream
+     * are exactly "ja", "JP", "JP" or "th", "TH", "TH" and script/extensions
+     * fields are empty, this method supplies <code>UNICODE_LOCALE_EXTENSION</code>
+     * "ca"/"japanese" (calendar type is "japanese") or "nu"/"thai" (number script
+     * type is "thai"). See <a href="Locale.html#special_cases_constructor"/>Special Cases</a>
+     * for more information.
+     *
+     * @return an instance of <code>Locale</code> equivalent to
+     * the deserialized <code>Locale</code>.
+     * @throws java.io.ObjectStreamException
      */
     private Object readResolve() throws java.io.ObjectStreamException {
-        return getInstance(language, country, variant);
+        return getInstance(_baseLocale.getLanguage(), _baseLocale.getScript(),
+                _baseLocale.getRegion(), _baseLocale.getVariant(), _extensions);
     }
 
     private static volatile String[] isoLanguages = null;
 
     private static volatile String[] isoCountries = null;
 
-    /*
-     * Locale needs its own, locale insensitive version of toLowerCase to
-     * avoid circularity problems between Locale and String.
-     * The most straightforward algorithm is used. Look at optimizations later.
-     */
-    private String toLowerCase(String str) {
-        char[] buf = new char[str.length()];
-        for (int i = 0; i < buf.length; i++) {
-            buf[i] = Character.toLowerCase(str.charAt(i));
-        }
-        return new String( buf );
-    }
-
-    /*
-     * Locale needs its own, locale insensitive version of toUpperCase to
-     * avoid circularity problems between Locale and String.
-     * The most straightforward algorithm is used. Look at optimizations later.
-     */
-    private String toUpperCase(String str) {
-        char[] buf = new char[str.length()];
-        for (int i = 0; i < buf.length; i++) {
-            buf[i] = Character.toUpperCase(str.charAt(i));
-        }
-        return new String( buf );
-    }
-
-    private String convertOldISOCodes(String language) {
+    private static String convertOldISOCodes(String language) {
         // we accept both the old and the new ISO codes for the languages whose ISO
         // codes have changed, but we always store the OLD code, for backward compatibility
-        language = toLowerCase(language).intern();
+        language = AsciiUtil.toLowerString(language).intern();
         if (language == "he") {
             return "iw";
         } else if (language == "yi") {
@@ -1110,6 +2038,25 @@
         }
     }
 
+    private static LocaleExtensions getCompatibilityExtensions(String language, String script, String country, String variant) {
+        LocaleExtensions extensions = LocaleExtensions.EMPTY_EXTENSIONS;
+        // Special cases for backward compatibility support
+        if (AsciiUtil.caseIgnoreMatch(language, "ja")
+                && script.length() == 0
+                && AsciiUtil.caseIgnoreMatch(country, "JP")
+                && AsciiUtil.caseIgnoreMatch(variant, "JP")) {
+            // ja_JP_JP -> u-ca-japanese (calendar = japanese)
+            extensions = LocaleExtensions.CALENDAR_JAPANESE;
+        } else if (AsciiUtil.caseIgnoreMatch(language, "th")
+                && script.length() == 0
+                && AsciiUtil.caseIgnoreMatch(country, "TH")
+                && AsciiUtil.caseIgnoreMatch(variant, "TH")) {
+            // th_TH_TH -> u-nu-thai (numbersystem = thai)
+            extensions = LocaleExtensions.NUMBER_THAI;
+        }
+        return extensions;
+    }
+
     /**
      * Obtains a localized locale names from a LocaleNameProvider
      * implementation.
@@ -1133,6 +2080,8 @@
                 return localeNameProvider.getDisplayCountry(code, locale);
             case DISPLAY_VARIANT:
                 return localeNameProvider.getDisplayVariant(code, locale);
+            case DISPLAY_SCRIPT:
+                return localeNameProvider.getDisplayScript(code, locale);
             default:
                 assert false; // shouldn't happen
             }
@@ -1140,4 +2089,370 @@
             return null;
         }
     }
+
+    /**
+     * Enum for locale categories.  These locale categories are used to get/set
+     * the default locale for the specific functionality represented by the
+     * category.
+     *
+     * @see #getDefault(Locale.Category)
+     * @see #setDefault(Locale.Category, Locale)
+     * @since 1.7
+     */
+    public enum Category {
+
+        /**
+         * Category used to represent the default locale for
+         * displaying user interfaces.
+         */
+        DISPLAY,
+
+        /**
+         * Category used to represent the default locale for
+         * formatting dates, numbers, and/or currencies.
+         */
+        FORMAT,
+    }
+
+    /**
+     * <code>Builder</code> is used to build instances of <code>Locale</code>
+     * from values configured by the setters.  Unlike the <code>Locale</code>
+     * constructors, the <code>Builder</code> checks if a value configured by a
+     * setter satisfies the syntax requirements defined by the <code>Locale</code>
+     * class.  A <code>Locale</code> object created by a <code>Builder</code> is
+     * well-formed and can be transformed to a well-formed IETF BCP 47 language tag
+     * without losing information.
+     *
+     * <p><b>Note:</b> The <code>Locale</code> class does not provide any
+     * syntactic restrictions on variant, while BCP 47 requires each variant
+     * subtag to be 5 to 8 alphanumerics or a single numeric followed by 3
+     * alphanumerics.  The method <code>setVariant</code> throws
+     * <code>IllformedLocaleException</code> for a variant that does not satisfy
+     * this restriction. If it is necessary to support such a variant, use a
+     * Locale constructor.  However, keep in mind that a <code>Locale</code>
+     * object created this way might lose the variant information when
+     * transformed to a BCP 47 language tag.
+     *
+     * <p>The following example shows how to create a <code>Locale</code> object
+     * with the <code>Builder</code>.
+     * <blockquote>
+     * <pre>
+     *     Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build();
+     * </pre>
+     * </blockquote>
+     *
+     * <p>Builders can be reused; <code>clear()</code> resets all
+     * fields to their default values.
+     *
+     * @see Locale#forLanguageTag
+     * @since 1.7
+     */
+    public static final class Builder {
+        private InternalLocaleBuilder _locbld;
+
+        /**
+         * Constructs an empty Builder. The default value of all
+         * fields, extensions, and private use information is the
+         * empty string.
+         */
+        public Builder() {
+            _locbld = new InternalLocaleBuilder();
+        }
+
+        /**
+         * Resets the <code>Builder</code> to match the provided
+         * <code>locale</code>.  Existing state is discarded.
+         *
+         * <p>All fields of the locale must be well-formed, see {@link Locale}.
+         *
+         * <p>Locales with any ill-formed fields cause
+         * <code>IllformedLocaleException</code> to be thrown, except for the
+         * following three cases which are accepted for compatibility
+         * reasons:<ul>
+         * <li>Locale("ja", "JP", "JP") is treated as "ja-JP-u-ca-japanese"
+         * <li>Locale("th", "TH", "TH") is treated as "th-TH-u-nu-thai"
+         * <li>Locale("no", "NO", "NY") is treated as "nn-NO"</ul>
+         *
+         * @param locale the locale
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>locale</code> has
+         * any ill-formed fields.
+         * @throws NullPointerException if <code>locale</code> is null.
+         */
+        public Builder setLocale(Locale locale) {
+            try {
+                _locbld.setLocale(locale._baseLocale, locale._extensions);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Resets the Builder to match the provided IETF BCP 47
+         * language tag.  Discards the existing state.  Null and the
+         * empty string cause the builder to be reset, like {@link
+         * #clear}.  Grandfathered tags (see {@link
+         * Locale#forLanguageTag}) are converted to their canonical
+         * form before being processed.  Otherwise, the language tag
+         * must be well-formed (see {@link Locale}) or an exception is
+         * thrown (unlike <code>Locale.forLanguageTag</code>, which
+         * just discards ill-formed and following portions of the
+         * tag).
+         *
+         * @param languageTag the language tag
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>languageTag</code> is ill-formed
+         * @see Locale#forLanguageTag(String)
+         */
+        public Builder setLanguageTag(String languageTag) {
+            ParseStatus sts = new ParseStatus();
+            LanguageTag tag = LanguageTag.parse(languageTag, sts);
+            if (sts.isError()) {
+                throw new IllformedLocaleException(sts.getErrorMessage(), sts.getErrorIndex());
+            }
+            _locbld.setLanguageTag(tag);
+
+            return this;
+        }
+
+        /**
+         * Sets the language.  If <code>language</code> is the empty string or
+         * null, the language in this <code>Builder</code> is removed.  Otherwise,
+         * the language must be <a href="./Locale.html#def_language">well-formed</a>
+         * or an exception is thrown.
+         *
+         * <p>The typical language value is a two or three-letter language
+         * code as defined in ISO639.
+         *
+         * @param language the language
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>language</code> is ill-formed
+         */
+        public Builder setLanguage(String language) {
+            try {
+                _locbld.setLanguage(language);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Sets the script. If <code>script</code> is null or the empty string,
+         * the script in this <code>Builder</code> is removed.
+         * Otherwise, the script must be <a href="./Locale.html#def_script">well-formed</a> or an
+         * exception is thrown.
+         *
+         * <p>The typical script value is a four-letter script code as defined by ISO 15924.
+         *
+         * @param script the script
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>script</code> is ill-formed
+         */
+        public Builder setScript(String script) {
+            try {
+                _locbld.setScript(script);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Sets the region.  If region is null or the empty string, the region
+         * in this <code>Builder</code> is removed.  Otherwise,
+         * the region must be <a href="./Locale.html#def_region">well-formed</a> or an
+         * exception is thrown.
+         *
+         * <p>The typical region value is a two-letter ISO 3166 code or a
+         * three-digit UN M.49 area code.
+         *
+         * <p>The country value in the <code>Locale</code> created by the
+         * <code>Builder</code> is always normalized to upper case.
+         *
+         * @param region the region
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>region</code> is ill-formed
+         */
+        public Builder setRegion(String region) {
+            try {
+                _locbld.setRegion(region);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Sets the variant.  If variant is null or the empty string, the
+         * variant in this <code>Builder</code> is removed.  Otherwise, it
+         * must consist of one or more <a href="./Locale.html#def_variant">well-formed</a>
+         * subtags, or an exception is thrown.
+         *
+         * <p><b>Note:</b> This method checks if <code>variant</code>
+         * satisfies the IETF BCP 47 variant subtag's syntax requirements,
+         * and normalizes the value to lowercase letters.  However,
+         * the <code>Locale</code> class does not impose any syntactic
+         * restriction on variant, and the variant value in
+         * <code>Locale</code> is case sensitive.  To set such a variant,
+         * use a Locale constructor.
+         *
+         * @param variant the variant
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>variant</code> is ill-formed
+         */
+        public Builder setVariant(String variant) {
+            try {
+                _locbld.setVariant(variant);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Sets the extension for the given key. If the value is null or the
+         * empty string, the extension is removed.  Otherwise, the extension
+         * must be <a href="./Locale.html#def_extensions">well-formed</a> or an exception
+         * is thrown.
+         *
+         * <p><b>Note:</b> The key {@link Locale#UNICODE_LOCALE_EXTENSION
+         * UNICODE_LOCALE_EXTENSION} ('u') is used for the Unicode locale extension.
+         * Setting a value for this key replaces any existing Unicode locale key/type
+         * pairs with those defined in the extension.
+         *
+         * <p><b>Note:</b> The key {@link Locale#PRIVATE_USE_EXTENSION
+         * PRIVATE_USE_EXTENSION} ('x') is used for the private use code. To be
+         * well-formed, the value for this key needs only to have subtags of one to
+         * eight alphanumeric characters, not two to eight as in the general case.
+         *
+         * @param key the extension key
+         * @param value the extension value
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>key</code> is illegal
+         * or <code>value</code> is ill-formed
+         * @see #setUnicodeLocaleKeyword(String, String)
+         */
+        public Builder setExtension(char key, String value) {
+            try {
+                _locbld.setExtension(key, value);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Sets the Unicode locale keyword type for the given key.  If the type
+         * is null, the Unicode keyword is removed.  Otherwise, the key must be
+         * non-null and both key and type must be <a
+         * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
+         * is thrown.
+         *
+         * <p>Keys and types are converted to lower case.
+         *
+         * <p><b>Note</b>:Setting the 'u' extension via {@link #setExtension}
+         * replaces all Unicode locale keywords with those defined in the
+         * extension.
+         *
+         * @param key the Unicode locale key
+         * @param type the Unicode locale type
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>key</code> or <code>type</code>
+         * is ill-formed
+         * @throws NullPointerException if <code>key</code> is null
+         * @see #setExtension(char, String)
+         */
+        public Builder setUnicodeLocaleKeyword(String key, String type) {
+            try {
+                _locbld.setUnicodeLocaleKeyword(key, type);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Adds a unicode locale attribute, if not already present, otherwise
+         * has no effect.  The attribute must not be null and must be <a
+         * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
+         * is thrown.
+         *
+         * @param attribute the attribute
+         * @return This builder.
+         * @throws NullPointerException if <code>attribute</code> is null
+         * @throws IllformedLocaleException if <code>attribute</code> is ill-formed
+         * @see #setExtension(char, String)
+         */
+        public Builder addUnicodeLocaleAttribute(String attribute) {
+            try {
+                _locbld.addUnicodeLocaleAttribute(attribute);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Removes a unicode locale attribute, if present, otherwise has no
+         * effect.  The attribute must not be null and must be <a
+         * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
+         * is thrown.
+         *
+         * <p>Attribute comparision for removal is case-insensitive.
+         *
+         * @param attribute the attribute
+         * @return This builder.
+         * @throws NullPointerException if <code>attribute</code> is null
+         * @throws IllformedLocaleException if <code>attribute</code> is ill-formed
+         * @see #setExtension(char, String)
+         */
+        public Builder removeUnicodeLocaleAttribute(String attribute) {
+            try {
+                _locbld.removeUnicodeLocaleAttribute(attribute);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Resets the builder to its initial, empty state.
+         *
+         * @return This builder.
+         */
+        public Builder clear() {
+            _locbld.clear();
+            return this;
+        }
+
+        /**
+         * Resets the extensions to their initial, empty state.
+         * Language, script, region and variant are unchanged.
+         *
+         * @return This builder.
+         * @see #setExtension(char, String)
+         */
+        public Builder clearExtensions() {
+            _locbld.clearExtensions();
+            return this;
+        }
+
+        /**
+         * Returns an instance of <code>Locale</code> created from the fields set
+         * on this builder.
+         *
+         * <p>This applies the conversions listed in {@link Locale#forLanguageTag}
+         * when constructing a Locale. (Grandfathered tags are handled in
+         * {@link #setLanguageTag}.)
+         *
+         * @return A Locale.
+         */
+        public Locale build() {
+            BaseLocale baseloc = _locbld.getBaseLocale();
+            LocaleExtensions extensions = _locbld.getLocaleExtensions();
+            return Locale.getInstance(baseloc, extensions);
+        }
+    }
 }
--- a/src/share/classes/java/util/ResourceBundle.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/util/ResourceBundle.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -56,16 +56,18 @@
 import java.util.concurrent.ConcurrentMap;
 import java.util.jar.JarEntry;
 
+import sun.util.locale.BaseLocale;
+import sun.util.locale.LocaleExtensions;
+import sun.util.locale.LocaleObjectCache;
+
 
 /**
  *
- * Resource bundles contain locale-specific objects.
- * When your program needs a locale-specific resource,
- * a <code>String</code> for example, your program can load it
- * from the resource bundle that is appropriate for the
- * current user's locale. In this way, you can write
- * program code that is largely independent of the user's
- * locale isolating most, if not all, of the locale-specific
+ * Resource bundles contain locale-specific objects.  When your program needs a
+ * locale-specific resource, a <code>String</code> for example, your program can
+ * load it from the resource bundle that is appropriate for the current user's
+ * locale. In this way, you can write program code that is largely independent
+ * of the user's locale isolating most, if not all, of the locale-specific
  * information in resource bundles.
  *
  * <p>
@@ -854,87 +856,140 @@
     }
 
     /**
-     * Gets a resource bundle using the specified base name, locale, and class loader.
+     * Gets a resource bundle using the specified base name, locale, and class
+     * loader.
      *
-     * <p><a name="default_behavior"/>
-     * Conceptually, <code>getBundle</code> uses the following strategy for locating and instantiating
-     * resource bundles:
-     * <p>
-     * <code>getBundle</code> uses the base name, the specified locale, and the default
-     * locale (obtained from {@link java.util.Locale#getDefault() Locale.getDefault})
-     * to generate a sequence of <a name="candidates"><em>candidate bundle names</em></a>.
-     * If the specified locale's language, country, and variant are all empty
-     * strings, then the base name is the only candidate bundle name.
-     * Otherwise, the following sequence is generated from the attribute
-     * values of the specified locale (language1, country1, and variant1)
-     * and of the default locale (language2, country2, and variant2):
-     * <ul>
-     * <li> baseName + "_" + language1 + "_" + country1 + "_" + variant1
-     * <li> baseName + "_" + language1 + "_" + country1
-     * <li> baseName + "_" + language1
-     * <li> baseName + "_" + language2 + "_" + country2 + "_" + variant2
-     * <li> baseName + "_" + language2 + "_" + country2
-     * <li> baseName + "_" + language2
-     * <li> baseName
-     * </ul>
-     * <p>
-     * Candidate bundle names where the final component is an empty string are omitted.
-     * For example, if country1 is an empty string, the second candidate bundle name is omitted.
+     * <p><a name="default_behavior"/>This method behaves the same as calling
+     * {@link #getBundle(String, Locale, ClassLoader, Control)} passing a
+     * default instance of {@link Control}. The following describes this behavior.
      *
-     * <p>
-     * <code>getBundle</code> then iterates over the candidate bundle names to find the first
-     * one for which it can <em>instantiate</em> an actual resource bundle. For each candidate
-     * bundle name, it attempts to create a resource bundle:
-     * <ul>
-     * <li>
-     * First, it attempts to load a class using the candidate bundle name.
-     * If such a class can be found and loaded using the specified class loader, is assignment
-     * compatible with ResourceBundle, is accessible from ResourceBundle, and can be instantiated,
-     * <code>getBundle</code> creates a new instance of this class and uses it as the <em>result
-     * resource bundle</em>.
-     * <li>
-     * Otherwise, <code>getBundle</code> attempts to locate a property resource file.
-     * It generates a path name from the candidate bundle name by replacing all "." characters
-     * with "/" and appending the string ".properties".
-     * It attempts to find a "resource" with this name using
-     * {@link java.lang.ClassLoader#getResource(java.lang.String) ClassLoader.getResource}.
-     * (Note that a "resource" in the sense of <code>getResource</code> has nothing to do with
-     * the contents of a resource bundle, it is just a container of data, such as a file.)
-     * If it finds a "resource", it attempts to create a new
-     * {@link PropertyResourceBundle} instance from its contents.
-     * If successful, this instance becomes the <em>result resource bundle</em>.
-     * </ul>
+     * <p><code>getBundle</code> uses the base name, the specified locale, and
+     * the default locale (obtained from {@link java.util.Locale#getDefault()
+     * Locale.getDefault}) to generate a sequence of <a
+     * name="candidates"><em>candidate bundle names</em></a>.  If the specified
+     * locale's language, script, country, and variant are all empty strings,
+     * then the base name is the only candidate bundle name.  Otherwise, a list
+     * of candidate locales is generated from the attribute values of the
+     * specified locale (language, script, country and variant) and appended to
+     * the base name.  Typically, this will look like the following:
      *
-     * <p>
-     * If no result resource bundle has been found, a <code>MissingResourceException</code>
-     * is thrown.
+     * <pre>
+     *     baseName + "_" + language + "_" + script + "_" + country + "_" + variant
+     *     baseName + "_" + language + "_" + script + "_" + country
+     *     baseName + "_" + language + "_" + script
+     *     baseName + "_" + language + "_" + country + "_" + variant
+     *     baseName + "_" + language + "_" + country
+     *     baseName + "_" + language
+     * </pre>
      *
-     * <p><a name="parent_chain"/>
-     * Once a result resource bundle has been found, its <em>parent chain</em> is instantiated.
-     * <code>getBundle</code> iterates over the candidate bundle names that can be
-     * obtained by successively removing variant, country, and language
-     * (each time with the preceding "_") from the bundle name of the result resource bundle.
-     * As above, candidate bundle names where the final component is an empty string are omitted.
-     * With each of the candidate bundle names it attempts to instantiate a resource bundle, as
-     * described above.
-     * Whenever it succeeds, it calls the previously instantiated resource
+     * <p>Candidate bundle names where the final component is an empty string
+     * are omitted, along with the underscore.  For example, if country is an
+     * empty string, the second and the fifth candidate bundle names above
+     * would be omitted.  Also, if script is an empty string, the candidate names
+     * including script are omitted.  For example, a locale with language "de"
+     * and variant "JAVA" will produce candidate names with base name
+     * "MyResource" below.
+     *
+     * <pre>
+     *     MyResource_de__JAVA
+     *     MyResource_de
+     * </pre>
+     *
+     * In the case that the variant contains one or more underscores ('_'), a
+     * sequence of bundle names generated by truncating the last underscore and
+     * the part following it is inserted after a candidate bundle name with the
+     * original variant.  For example, for a locale with language "en", script
+     * "Latn, country "US" and variant "WINDOWS_VISTA", and bundle base name
+     * "MyResource", the list of candidate bundle names below is generated:
+     *
+     * <pre>
+     * MyResource_en_Latn_US_WINDOWS_VISTA
+     * MyResource_en_Latn_US_WINDOWS
+     * MyResource_en_Latn_US
+     * MyResource_en_Latn
+     * MyResource_en_US_WINDOWS_VISTA
+     * MyResource_en_US_WINDOWS
+     * MyResource_en_US
+     * MyResource_en
+     * </pre>
+     *
+     * <blockquote><b>Note:</b> For some <code>Locale</code>s, the list of
+     * candidate bundle names contains extra names, or the order of bundle names
+     * is slightly modified.  See the description of the default implementation
+     * of {@link Control#getCandidateLocales(String, Locale)
+     * getCandidateLocales} for details.</blockquote>
+     *
+     * <p><code>getBundle</code> then iterates over the candidate bundle names
+     * to find the first one for which it can <em>instantiate</em> an actual
+     * resource bundle. It uses the default controls' {@link Control#getFormats
+     * getFormats} method, which generates two bundle names for each generated
+     * name, the first a class name and the second a properties file name. For
+     * each candidate bundle name, it attempts to create a resource bundle:
+     *
+     * <ul><li>First, it attempts to load a class using the generated class name.
+     * If such a class can be found and loaded using the specified class
+     * loader, is assignment compatible with ResourceBundle, is accessible from
+     * ResourceBundle, and can be instantiated, <code>getBundle</code> creates a
+     * new instance of this class and uses it as the <em>result resource
+     * bundle</em>.
+     *
+     * <li>Otherwise, <code>getBundle</code> attempts to locate a property
+     * resource file using the generated properties file name.  It generates a
+     * path name from the candidate bundle name by replacing all "." characters
+     * with "/" and appending the string ".properties".  It attempts to find a
+     * "resource" with this name using {@link
+     * java.lang.ClassLoader#getResource(java.lang.String)
+     * ClassLoader.getResource}.  (Note that a "resource" in the sense of
+     * <code>getResource</code> has nothing to do with the contents of a
+     * resource bundle, it is just a container of data, such as a file.)  If it
+     * finds a "resource", it attempts to create a new {@link
+     * PropertyResourceBundle} instance from its contents.  If successful, this
+     * instance becomes the <em>result resource bundle</em>.  </ul>
+     *
+     * <p>This continues until a result resource bundle is instantiated or the
+     * list of candidate bundle names is exhausted.  If no matching resource
+     * bundle is found, the default control's {@link Control#getFallbackLocale
+     * getFallbackLocale} method is called, which returns the current default
+     * locale.  A new sequence of candidate locale names is generated using this
+     * locale and and searched again, as above.
+     *
+     * <p>If still no result bundle is found, the base name alone is looked up. If
+     * this still fails, a <code>MissingResourceException</code> is thrown.
+     *
+     * <p><a name="parent_chain"/> Once a result resource bundle has been found,
+     * its <em>parent chain</em> is instantiated.  If the result bundle already
+     * has a parent (perhaps because it was returned from a cache) the chain is
+     * complete.
+     *
+     * <p>Otherwise, <code>getBundle</code> examines the remainder of the
+     * candidate locale list that was used during the pass that generated the
+     * result resource bundle.  (As before, candidate bundle names where the
+     * final component is an empty string are omitted.)  When it comes to the
+     * end of the candidate list, it tries the plain bundle name.  With each of the
+     * candidate bundle names it attempts to instantiate a resource bundle (first
+     * looking for a class and then a properties file, as described above).
+     *
+     * <p>Whenever it succeeds, it calls the previously instantiated resource
      * bundle's {@link #setParent(java.util.ResourceBundle) setParent} method
-     * with the new resource bundle, unless the previously instantiated resource
-     * bundle already has a non-null parent.
+     * with the new resource bundle.  This continues until the list of names
+     * is exhausted or the current bundle already has a non-null parent.
      *
-     * <p>
-     * <code>getBundle</code> caches instantiated resource bundles and
-     * may return the same resource bundle instance multiple
-     * times.
+     * <p>Once the parent chain is complete, the bundle is returned.
      *
-     * <p>
-     * The <code>baseName</code> argument should be a fully qualified class name. However, for
-     * compatibility with earlier versions, Sun's Java SE Runtime Environments do not verify this,
-     * and so it is possible to access <code>PropertyResourceBundle</code>s by specifying a
-     * path name (using "/") instead of a fully qualified class name (using ".").
+     * <p><b>Note:</b> <code>getBundle</code> caches instantiated resource
+     * bundles and might return the same resource bundle instance multiple times.
+     *
+     * <p><b>Note:</b>The <code>baseName</code> argument should be a fully
+     * qualified class name. However, for compatibility with earlier versions,
+     * Sun's Java SE Runtime Environments do not verify this, and so it is
+     * possible to access <code>PropertyResourceBundle</code>s by specifying a
+     * path name (using "/") instead of a fully qualified class name (using
+     * ".").
      *
      * <p><a name="default_behavior_example"/>
-     * <strong>Example:</strong><br>The following class and property files are provided:
+     * <strong>Example:</strong>
+     * <p>
+     * The following class and property files are provided:
      * <pre>
      *     MyResources.class
      *     MyResources.properties
@@ -944,22 +999,26 @@
      *     MyResources_en.properties
      *     MyResources_es_ES.class
      * </pre>
-     * The contents of all files are valid (that is, public non-abstract subclasses of <code>ResourceBundle</code> for
-     * the ".class" files, syntactically correct ".properties" files).
-     * The default locale is <code>Locale("en", "GB")</code>.
-     * <p>
-     * Calling <code>getBundle</code> with the shown locale argument values instantiates
-     * resource bundles from the following sources:
-     * <ul>
-     * <li>Locale("fr", "CH"): result MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class
-     * <li>Locale("fr", "FR"): result MyResources_fr.properties, parent MyResources.class
-     * <li>Locale("de", "DE"): result MyResources_en.properties, parent MyResources.class
-     * <li>Locale("en", "US"): result MyResources_en.properties, parent MyResources.class
-     * <li>Locale("es", "ES"): result MyResources_es_ES.class, parent MyResources.class
-     * </ul>
-     * <p>The file MyResources_fr_CH.properties is never used because it is hidden by
-     * MyResources_fr_CH.class. Likewise, MyResources.properties is also hidden by
-     * MyResources.class.
+     *
+     * The contents of all files are valid (that is, public non-abstract
+     * subclasses of <code>ResourceBundle</code> for the ".class" files,
+     * syntactically correct ".properties" files).  The default locale is
+     * <code>Locale("en", "GB")</code>.
+     *
+     * <p>Calling <code>getBundle</code> with the locale arguments below will
+     * instantiate resource bundles as follows:
+     *
+     * <table>
+     * <tr><td>Locale("fr", "CH")</td><td>MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class</td></tr>
+     * <tr><td>Locale("fr", "FR")</td><td>MyResources_fr.properties, parent MyResources.class</td></tr>
+     * <tr><td>Locale("de", "DE")</td><td>MyResources_en.properties, parent MyResources.class</td></tr>
+     * <tr><td>Locale("en", "US")</td><td>MyResources_en.properties, parent MyResources.class</td></tr>
+     * <tr><td>Locale("es", "ES")</td><td>MyResources_es_ES.class, parent MyResources.class</td></tr>
+     * </table>
+     *
+     * <p>The file MyResources_fr_CH.properties is never used because it is
+     * hidden by the MyResources_fr_CH.class. Likewise, MyResources.properties
+     * is also hidden by MyResources.class.
      *
      * @param baseName the base name of the resource bundle, a fully qualified class name
      * @param locale the locale for which a resource bundle is desired
@@ -1095,8 +1154,6 @@
      * href="./ResourceBundle.html#parent_chain">parent chain</a> is
      * instantiated based on the list of candidate locales from which it was
      * found. Finally, the bundle is returned to the caller.</li>
-     *
-     *
      * </ol>
      *
      * <p>During the resource bundle loading process above, this factory
@@ -1119,7 +1176,6 @@
      * {@link Control#getTimeToLive(String,Locale)
      * control.getTimeToLive} for details.
      *
-     *
      * <p>The following is an example of the bundle loading process with the
      * default <code>ResourceBundle.Control</code> implementation.
      *
@@ -1131,7 +1187,6 @@
      * <li>Available resource bundles:
      * <code>foo/bar/Messages_fr.properties</code> and
      * <code>foo/bar/Messages.properties</code></li>
-     *
      * </ul>
      *
      * <p>First, <code>getBundle</code> tries loading a resource bundle in
@@ -1811,8 +1866,8 @@
      * handleGetObject} method returns <code>null</code>. Once the
      * <code>Set</code> has been created, the value is kept in this
      * <code>ResourceBundle</code> in order to avoid producing the
-     * same <code>Set</code> in the next calls.  Override this method
-     * in subclass implementations for faster handling.
+     * same <code>Set</code> in subsequent calls. Subclasses can
+     * override this method for faster handling.
      *
      * @return a <code>Set</code> of the keys contained only in this
      *        <code>ResourceBundle</code>
@@ -2177,24 +2232,133 @@
          * <code>ResourceBundle.getBundle</code> factory method loads only
          * the base bundle as the resulting resource bundle.
          *
-         * <p>It is not a requirement to return an immutable
-         * (unmodifiable) <code>List</code>. However, the returned
-         * <code>List</code> must not be mutated after it has been
-         * returned by <code>getCandidateLocales</code>.
+         * <p>It is not a requirement to return an immutable (unmodifiable)
+         * <code>List</code>. However, the returned <code>List</code> must not
+         * be mutated after it has been returned by
+         * <code>getCandidateLocales</code>.
          *
          * <p>The default implementation returns a <code>List</code> containing
-         * <code>Locale</code>s in the following sequence:
-         * <pre>
-         *     Locale(language, country, variant)
-         *     Locale(language, country)
-         *     Locale(language)
-         *     Locale.ROOT
-         * </pre>
-         * where <code>language</code>, <code>country</code> and
-         * <code>variant</code> are the language, country and variant values
-         * of the given <code>locale</code>, respectively. Locales where the
+         * <code>Locale</code>s using the rules described below.  In the
+         * description below, <em>L</em>, <em>S</em>, <em>C</em> and <em>V</em>
+         * respectively represent non-empty language, script, country, and
+         * variant.  For example, [<em>L</em>, <em>C</em>] represents a
+         * <code>Locale</code> that has non-empty values only for language and
+         * country.  The form <em>L</em>("xx") represents the (non-empty)
+         * language value is "xx".  For all cases, <code>Locale</code>s whose
          * final component values are empty strings are omitted.
          *
+         * <ol><li>For an input <code>Locale</code> with an empty script value,
+         * append candidate <code>Locale</code>s by omitting the final component
+         * one by one as below:
+         *
+         * <ul>
+         * <li> [<em>L</em>, <em>C</em>, <em>V</em>]
+         * <li> [<em>L</em>, <em>C</em>]
+         * <li> [<em>L</em>]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * <li>For an input <code>Locale</code> with a non-empty script value,
+         * append candidate <code>Locale</code>s by omitting the final component
+         * up to language, then append candidates generated from the
+         * <code>Locale</code> with country and variant restored:
+         *
+         * <ul>
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V</em>]
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>]
+         * <li> [<em>L</em>, <em>S</em>]
+         * <li> [<em>L</em>, <em>C</em>, <em>V</em>]
+         * <li> [<em>L</em>, <em>C</em>]
+         * <li> [<em>L</em>]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * <li>For an input <code>Locale</code> with a variant value consisting
+         * of multiple subtags separated by underscore, generate candidate
+         * <code>Locale</code>s by omitting the variant subtags one by one, then
+         * insert them after every occurence of <code> Locale</code>s with the
+         * full variant value in the original list.  For example, if the
+         * the variant consists of two subtags <em>V1</em> and <em>V2</em>:
+         *
+         * <ul>
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>]
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>]
+         * <li> [<em>L</em>, <em>S</em>]
+         * <li> [<em>L</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]
+         * <li> [<em>L</em>, <em>C</em>, <em>V1</em>]
+         * <li> [<em>L</em>, <em>C</em>]
+         * <li> [<em>L</em>]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * <li>Special cases for Chinese.  When an input <code>Locale</code> has the
+         * language "zh" (Chinese) and an empty script value, either "Hans" (Simplified) or
+         * "Hant" (Traditional) might be supplied, depending on the country.
+         * When the country is "CN" (China) or "SG" (Singapore), "Hans" is supplied.
+         * When the country is "HK" (Hong Kong SAR China), "MO" (Macau SAR China),
+         * or "TW" (Taiwan), "Hant" is supplied.  For all other countries or when the country
+         * is empty, no script is supplied.  For example, for <code>Locale("zh", "CN")
+         * </code>, the candidate list will be:
+         * <ul>
+         * <li> [<em>L</em>("zh"), <em>S</em>("Hans"), <em>C</em>("CN")]
+         * <li> [<em>L</em>("zh"), <em>S</em>("Hans")]
+         * <li> [<em>L</em>("zh"), <em>C</em>("CN")]
+         * <li> [<em>L</em>("zh")]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * For <code>Locale("zh", "TW")</code>, the candidate list will be:
+         * <ul>
+         * <li> [<em>L</em>("zh"), <em>S</em>("Hant"), <em>C</em>("TW")]
+         * <li> [<em>L</em>("zh"), <em>S</em>("Hant")]
+         * <li> [<em>L</em>("zh"), <em>C</em>("TW")]
+         * <li> [<em>L</em>("zh")]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * <li>Special cases for Norwegian.  Both <code>Locale("no", "NO",
+         * "NY")</code> and <code>Locale("nn", "NO")</code> represent Norwegian
+         * Nynorsk.  When a locale's language is "nn", the standard candidate
+         * list is generated up to [<em>L</em>("nn")], and then the following
+         * candidates are added:
+         *
+         * <ul><li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("NY")]
+         * <li> [<em>L</em>("no"), <em>C</em>("NO")]
+         * <li> [<em>L</em>("no")]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * If the locale is exactly <code>Locale("no", "NO", "NY")</code>, it is first
+         * converted to <code>Locale("nn", "NO")</code> and then the above procedure is
+         * followed.
+         *
+         * <p>Also, Java treats the language "no" as a synonym of Norwegian
+         * Bokm&#xE5;l "nb".  Except for the single case <code>Locale("no",
+         * "NO", "NY")</code> (handled above), when an input <code>Locale</code>
+         * has language "no" or "nb", candidate <code>Locale</code>s with
+         * language code "no" and "nb" are interleaved, first using the
+         * requested language, then using its synonym. For example,
+         * <code>Locale("nb", "NO", "POSIX")</code> generates the following
+         * candidate list:
+         *
+         * <ul>
+         * <li> [<em>L</em>("nb"), <em>C</em>("NO"), <em>V</em>("POSIX")]
+         * <li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("POSIX")]
+         * <li> [<em>L</em>("nb"), <em>C</em>("NO")]
+         * <li> [<em>L</em>("no"), <em>C</em>("NO")]
+         * <li> [<em>L</em>("nb")]
+         * <li> [<em>L</em>("no")]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * <code>Locale("no", "NO", "POSIX")</code> would generate the same list
+         * except that locales with "no" would appear before the corresponding
+         * locales with "nb".</li>
+         *
+         * </li>
+         * </ol>
+         *
          * <p>The default implementation uses an {@link ArrayList} that
          * overriding implementations may modify before returning it to the
          * caller. However, a subclass must not modify it after it has
@@ -2231,24 +2395,119 @@
             if (baseName == null) {
                 throw new NullPointerException();
             }
-            String language = locale.getLanguage();
-            String country = locale.getCountry();
-            String variant = locale.getVariant();
+            return new ArrayList<Locale>(CANDIDATES_CACHE.get(locale.getBaseLocale()));
+        }
 
-            List<Locale> locales = new ArrayList<Locale>(4);
-            if (variant.length() > 0) {
-                locales.add(locale);
+        private static final CandidateListCache CANDIDATES_CACHE = new CandidateListCache();
+
+        private static class CandidateListCache extends LocaleObjectCache<BaseLocale, List<Locale>> {
+            protected List<Locale> createObject(BaseLocale base) {
+                String language = base.getLanguage();
+                String script = base.getScript();
+                String region = base.getRegion();
+                String variant = base.getVariant();
+
+                // Special handling for Norwegian
+                boolean isNorwegianBokmal = false;
+                boolean isNorwegianNynorsk = false;
+                if (language.equals("no")) {
+                    if (region.equals("NO") && variant.equals("NY")) {
+                        variant = "";
+                        isNorwegianNynorsk = true;
+                    } else {
+                        isNorwegianBokmal = true;
+                    }
+                }
+                if (language.equals("nb") || isNorwegianBokmal) {
+                    List<Locale> tmpList = getDefaultList("nb", script, region, variant);
+                    // Insert a locale replacing "nb" with "no" for every list entry
+                    List<Locale> bokmalList = new LinkedList<Locale>();
+                    for (Locale l : tmpList) {
+                        bokmalList.add(l);
+                        if (l.getLanguage().length() == 0) {
+                            break;
+                        }
+                        bokmalList.add(Locale.getInstance("no", l.getScript(), l.getCountry(),
+                                l.getVariant(), LocaleExtensions.EMPTY_EXTENSIONS));
+                    }
+                    return bokmalList;
+                } else if (language.equals("nn") || isNorwegianNynorsk) {
+                    // Insert no_NO_NY, no_NO, no after nn
+                    List<Locale> nynorskList = getDefaultList("nn", script, region, variant);
+                    int idx = nynorskList.size() - 1;
+                    nynorskList.add(idx++, Locale.getInstance("no", "NO", "NY"));
+                    nynorskList.add(idx++, Locale.getInstance("no", "NO", ""));
+                    nynorskList.add(idx++, Locale.getInstance("no", "", ""));
+                    return nynorskList;
+                }
+                // Special handling for Chinese
+                else if (language.equals("zh")) {
+                    if (script.length() == 0 && region.length() > 0) {
+                        // Supply script for users who want to use zh_Hans/zh_Hant
+                        // as bundle names (recommended for Java7+)
+                        if (region.equals("TW") || region.equals("HK") || region.equals("MO")) {
+                            script = "Hant";
+                        } else if (region.equals("CN") || region.equals("SG")) {
+                            script = "Hans";
+                        }
+                    } else if (script.length() > 0 && region.length() == 0) {
+                        // Supply region(country) for users who still package Chinese
+                        // bundles using old convension.
+                        if (script.equals("Hans")) {
+                            region = "CN";
+                        } else if (script.equals("Hant")) {
+                            region = "TW";
+                        }
+                    }
+                }
+
+                return getDefaultList(language, script, region, variant);
             }
-            if (country.length() > 0) {
-                locales.add((locales.size() == 0) ?
-                            locale : Locale.getInstance(language, country, ""));
+
+            private static List<Locale> getDefaultList(String language, String script, String region, String variant) {
+                List<String> variants = null;
+
+                if (variant.length() > 0) {
+                    variants = new LinkedList<String>();
+                    int idx = variant.length();
+                    while (idx != -1) {
+                        variants.add(variant.substring(0, idx));
+                        idx = variant.lastIndexOf('_', --idx);
+                    }
+                }
+
+                LinkedList<Locale> list = new LinkedList<Locale>();
+
+                if (variants != null) {
+                    for (String v : variants) {
+                        list.add(Locale.getInstance(language, script, region, v, LocaleExtensions.EMPTY_EXTENSIONS));
+                    }
+                }
+                if (region.length() > 0) {
+                    list.add(Locale.getInstance(language, script, region, "", LocaleExtensions.EMPTY_EXTENSIONS));
+                }
+                if (script.length() > 0) {
+                    list.add(Locale.getInstance(language, script, "", "", LocaleExtensions.EMPTY_EXTENSIONS));
+
+                    // With script, after truncating variant, region and script,
+                    // start over without script.
+                    if (variants != null) {
+                        for (String v : variants) {
+                            list.add(Locale.getInstance(language, "", region, v, LocaleExtensions.EMPTY_EXTENSIONS));
+                        }
+                    }
+                    if (region.length() > 0) {
+                        list.add(Locale.getInstance(language, "", region, "", LocaleExtensions.EMPTY_EXTENSIONS));
+                    }
+                }
+                if (language.length() > 0) {
+                    list.add(Locale.getInstance(language, "", "", "", LocaleExtensions.EMPTY_EXTENSIONS));
+                }
+                // Add root locale at the end
+                list.add(Locale.ROOT);
+
+                return list;
             }
-            if (language.length() > 0) {
-                locales.add((locales.size() == 0) ?
-                            locale : Locale.getInstance(language, "", ""));
-            }
-            locales.add(Locale.ROOT);
-            return locales;
         }
 
         /**
@@ -2606,13 +2865,14 @@
          *
          * <p>This implementation returns the following value:
          * <pre>
-         *     baseName + "_" + language + "_" + country + "_" + variant
+         *     baseName + "_" + language + "_" + script + "_" + country + "_" + variant
          * </pre>
-         * where <code>language</code>, <code>country</code> and
-         * <code>variant</code> are the language, country and variant values
-         * of <code>locale</code>, respectively. Final component values that
-         * are empty Strings are omitted along with the preceding '_'. If
-         * all of the values are empty strings, then <code>baseName</code>
+         * where <code>language</code>, <code>script</code>, <code>country</code>,
+         * and <code>variant</code> are the language, script, country, and variant
+         * values of <code>locale</code>, respectively. Final component values that
+         * are empty Strings are omitted along with the preceding '_'.  When the
+         * script is empty, the script value is ommitted along with the preceding '_'.
+         * If all of the values are empty strings, then <code>baseName</code>
          * is returned.
          *
          * <p>For example, if <code>baseName</code> is
@@ -2643,6 +2903,7 @@
             }
 
             String language = locale.getLanguage();
+            String script = locale.getScript();
             String country = locale.getCountry();
             String variant = locale.getVariant();
 
@@ -2652,12 +2913,22 @@
 
             StringBuilder sb = new StringBuilder(baseName);
             sb.append('_');
-            if (variant != "") {
-                sb.append(language).append('_').append(country).append('_').append(variant);
-            } else if (country != "") {
-                sb.append(language).append('_').append(country);
+            if (script != "") {
+                if (variant != "") {
+                    sb.append(language).append('_').append(script).append('_').append(country).append('_').append(variant);
+                } else if (country != "") {
+                    sb.append(language).append('_').append(script).append('_').append(country);
+                } else {
+                    sb.append(language).append('_').append(script);
+                }
             } else {
-                sb.append(language);
+                if (variant != "") {
+                    sb.append(language).append('_').append(country).append('_').append(variant);
+                } else if (country != "") {
+                    sb.append(language).append('_').append(country);
+                } else {
+                    sb.append(language);
+                }
             }
             return sb.toString();
 
--- a/src/share/classes/java/util/Scanner.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/util/Scanner.java	Sat Sep 25 12:00:05 2010 -0700
@@ -582,7 +582,7 @@
         matcher = delimPattern.matcher(buf);
         matcher.useTransparentBounds(true);
         matcher.useAnchoringBounds(false);
-        useLocale(Locale.getDefault());
+        useLocale(Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -2642,7 +2642,7 @@
      */
     public Scanner reset() {
         delimPattern = WHITESPACE_PATTERN;
-        useLocale(Locale.getDefault());
+        useLocale(Locale.getDefault(Locale.Category.FORMAT));
         useRadix(10);
         clearCaches();
         return this;
--- a/src/share/classes/java/util/TimeZone.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/util/TimeZone.java	Sat Sep 25 12:00:05 2010 -0700
@@ -312,7 +312,7 @@
      * @since 1.2
      */
     public final String getDisplayName() {
-        return getDisplayName(false, LONG, Locale.getDefault());
+        return getDisplayName(false, LONG, Locale.getDefault(Locale.Category.DISPLAY));
     }
 
     /**
@@ -342,7 +342,7 @@
      * @since 1.2
      */
     public final String getDisplayName(boolean daylight, int style) {
-        return getDisplayName(daylight, style, Locale.getDefault());
+        return getDisplayName(daylight, style, Locale.getDefault(Locale.Category.DISPLAY));
     }
 
     /**
--- a/src/share/classes/java/util/spi/LocaleNameProvider.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/util/spi/LocaleNameProvider.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -44,22 +44,23 @@
     }
 
     /**
-     * Returns a localized name for the given ISO 639 language code and the
-     * given locale that is appropriate for display to the user.
+     * Returns a localized name for the given <a href="http://www.rfc-editor.org/rfc/bcp/bcp47.txt">
+     * IETF BCP47</a> language code and the given locale that is appropriate for
+     * display to the user.
      * For example, if <code>languageCode</code> is "fr" and <code>locale</code>
      * is en_US, getDisplayLanguage() will return "French"; if <code>languageCode</code>
      * is "en" and <code>locale</code> is fr_FR, getDisplayLanguage() will return "anglais".
      * If the name returned cannot be localized according to <code>locale</code>,
      * (say, the provider does not have a Japanese name for Croatian),
      * this method returns null.
-     * @param languageCode the ISO 639 language code string in the form of two
+     * @param languageCode the language code string in the form of two to eight
      *     lower-case letters between 'a' (U+0061) and 'z' (U+007A)
      * @param locale the desired locale
      * @return the name of the given language code for the specified locale, or null if it's not
      *     available.
      * @exception NullPointerException if <code>languageCode</code> or <code>locale</code> is null
      * @exception IllegalArgumentException if <code>languageCode</code> is not in the form of
-     *     two lower-case letters, or <code>locale</code> isn't
+     *     two or three lower-case letters, or <code>locale</code> isn't
      *     one of the locales returned from
      *     {@link java.util.spi.LocaleServiceProvider#getAvailableLocales()
      *     getAvailableLocales()}.
@@ -68,22 +69,52 @@
     public abstract String getDisplayLanguage(String languageCode, Locale locale);
 
     /**
-     * Returns a localized name for the given ISO 3166 country code and the
-     * given locale that is appropriate for display to the user.
+     * Returns a localized name for the given <a href="http://www.rfc-editor.org/rfc/bcp/bcp47.txt">
+     * IETF BCP47</a> script code and the given locale that is appropriate for
+     * display to the user.
+     * For example, if <code>scriptCode</code> is "Latn" and <code>locale</code>
+     * is en_US, getDisplayScript() will return "Latin"; if <code>scriptCode</code>
+     * is "Cyrl" and <code>locale</code> is fr_FR, getDisplayScript() will return "cyrillique".
+     * If the name returned cannot be localized according to <code>locale</code>,
+     * (say, the provider does not have a Japanese name for Cyrillic),
+     * this method returns null.
+     * @param scriptCode the four letter script code string in the form of title-case
+     *     letters (the first letter is upper-case character between 'A' (U+0041) and
+     *     'Z' (U+005A) followed by three lower-case character between 'a' (U+0061)
+     *     and 'z' (U+007A)).
+     * @param locale the desired locale
+     * @return the name of the given script code for the specified locale, or null if it's not
+     *     available.
+     * @exception NullPointerException if <code>scriptCode</code> or <code>locale</code> is null
+     * @exception IllegalArgumentException if <code>scriptCode</code> is not in the form of
+     *     four title case letters, or <code>locale</code> isn't
+     *     one of the locales returned from
+     *     {@link java.util.spi.LocaleServiceProvider#getAvailableLocales()
+     *     getAvailableLocales()}.
+     * @see java.util.Locale#getDisplayScript(java.util.Locale)
+     * @since 1.7
+     */
+    public abstract String getDisplayScript(String scriptCode, Locale locale);
+
+    /**
+     * Returns a localized name for the given <a href="http://www.rfc-editor.org/rfc/bcp/bcp47.txt">
+     * IETF BCP47</a> region code (either ISO 3166 country code or UN M.49 area
+     * codes) and the given locale that is appropriate for display to the user.
      * For example, if <code>countryCode</code> is "FR" and <code>locale</code>
      * is en_US, getDisplayCountry() will return "France"; if <code>countryCode</code>
      * is "US" and <code>locale</code> is fr_FR, getDisplayCountry() will return "Etats-Unis".
      * If the name returned cannot be localized according to <code>locale</code>,
      * (say, the provider does not have a Japanese name for Croatia),
      * this method returns null.
-     * @param countryCode the ISO 3166 country code string in the form of two
-     *     upper-case letters between 'A' (U+0041) and 'Z' (U+005A)
+     * @param countryCode the country(region) code string in the form of two
+     *     upper-case letters between 'A' (U+0041) and 'Z' (U+005A) or the UN M.49 area code
+     *     in the form of three digit letters between '0' (U+0030) and '9' (U+0039).
      * @param locale the desired locale
      * @return the name of the given country code for the specified locale, or null if it's not
      *     available.
      * @exception NullPointerException if <code>countryCode</code> or <code>locale</code> is null
      * @exception IllegalArgumentException if <code>countryCode</code> is not in the form of
-     *     two upper-case letters, or <code>locale</code> isn't
+     *     two upper-case letters or three digit letters, or <code>locale</code> isn't
      *     one of the locales returned from
      *     {@link java.util.spi.LocaleServiceProvider#getAvailableLocales()
      *     getAvailableLocales()}.
--- a/src/share/classes/java/util/spi/LocaleServiceProvider.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/java/util/spi/LocaleServiceProvider.java	Sat Sep 25 12:00:05 2010 -0700
@@ -86,18 +86,19 @@
  * Otherwise, they call the <code>getAvailableLocales()</code> methods of
  * installed providers for the appropriate interface to find one that
  * supports the requested locale. If such a provider is found, its other
- * methods are called to obtain the requested object or name. If neither
- * the Java runtime environment itself nor an installed provider supports
- * the requested locale, a fallback locale is constructed by replacing the
- * first of the variant, country, or language strings of the locale that's
- * not an empty string with an empty string, and the lookup process is
- * restarted. In the case that the variant contains one or more '_'s, the
- * fallback locale is constructed by replacing the variant with a new variant
- * which eliminates the last '_' and the part following it.  Even if a
- * fallback occurs, methods that return requested objects or name are
- * invoked with the original locale before the fallback.The Java runtime
- * environment must support the root locale for all locale sensitive services
- * in order to guarantee that this process terminates.
+ * methods are called to obtain the requested object or name.  When checking
+ * whether a locale is supported, the locale's extensions are ignored.
+ * If neither the Java runtime environment itself nor an installed provider
+ * supports the requested locale, the methods go through a list of candidate
+ * locales and repeat the availability check for each until a match is found.
+ * The algorithm used for creating a list of candidate locales is same as
+ * the one used by <code>ResourceBunlde</code> by default (see
+ * {@link java.util.ResourceBundle.Control#getCandidateLocales getCandidateLocales}
+ * for the details).  Even if a locale is resolved from the candidate list,
+ * methods that return requested objects or names are invoked with the original
+ * requested locale including extensions.  The Java runtime environment must
+ * support the root locale for all locale sensitive services in order to
+ * guarantee that this process terminates.
  * <p>
  * Providers of names (but not providers of other objects) are allowed to
  * return null for some name requests even for locales that they claim to
@@ -124,6 +125,11 @@
     /**
      * Returns an array of all locales for which this locale service provider
      * can provide localized objects or names.
+     * <p>
+     * <b>Note:</b> Extensions in a <code>Locale</code> are ignored during
+     * service provider lookup.  So the array returned by this method should
+     * not include two or more <code>Locale</code> objects only differing in
+     * their extensions.
      *
      * @return An array of all locales for which this locale service provider
      * can provide localized objects or names.
--- a/src/share/classes/javax/sound/midi/MidiDevice.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/javax/sound/midi/MidiDevice.java	Sat Sep 25 12:00:05 2010 -0700
@@ -204,6 +204,9 @@
      * MIDI data.  The returned receiver must be closed when the application
      * has finished using it.
      *
+     * <p>Usually the returned receiver implements
+     * the {@code MidiDeviceReceiver} interface.
+     *
      * <p>Obtaining a <code>Receiver</code> with this method does not
      * open the device. To be able to use the device, it has to be
      * opened explicitly by calling {@link #open}. Also, closing the
@@ -223,6 +226,10 @@
      * connected with this MidiDevice.
      * A receiver can be removed
      * from the device by closing it.
+     *
+     * <p>Usually the returned receivers implement
+     * the {@code MidiDeviceReceiver} interface.
+     *
      * @return an unmodifiable list of the open receivers
      * @since 1.5
      */
@@ -234,6 +241,9 @@
      * MIDI data  The returned transmitter must be closed when the application
      * has finished using it.
      *
+     * <p>Usually the returned transmitter implements
+     * the {@code MidiDeviceTransmitter} interface.
+     *
      * <p>Obtaining a <code>Transmitter</code> with this method does not
      * open the device. To be able to use the device, it has to be
      * opened explicitly by calling {@link #open}. Also, closing the
@@ -253,6 +263,10 @@
      * connected with this MidiDevice.
      * A transmitter can be removed
      * from the device by closing it.
+     *
+     * <p>Usually the returned transmitters implement
+     * the {@code MidiDeviceTransmitter} interface.
+     *
      * @return an unmodifiable list of the open transmitters
      * @since 1.5
      */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/sound/midi/MidiDeviceReceiver.java	Sat Sep 25 12:00:05 2010 -0700
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * 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 javax.sound.midi;
+
+/**
+ * <p>{@code MidiDeviceReceiver} is a {@code Receiver} which represents
+ * a MIDI input connector of a {@code MidiDevice}
+ * (see {@link MidiDevice#getReceiver()}).
+ *
+ * @since 1.7
+ */
+public interface MidiDeviceReceiver extends Receiver {
+    /** Obtains a MidiDevice object which is an owner of this Receiver.
+     */
+    public MidiDevice getMidiDevice();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/sound/midi/MidiDeviceTransmitter.java	Sat Sep 25 12:00:05 2010 -0700
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * 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 javax.sound.midi;
+
+
+/**
+ * <p>{@code MidiDeviceTransmitter} is a {@code Transmitter} which represents
+ * a MIDI input connector of a {@code MidiDevice}
+ * (see {@link MidiDevice#getTransmitter()}).
+ *
+ * @since 1.7
+ */
+public interface MidiDeviceTransmitter extends Transmitter {
+
+    /** Obtains a MidiDevice object which is an owner of this Transmitter.
+     */
+    public MidiDevice getMidiDevice();
+}
--- a/src/share/classes/javax/sound/midi/MidiSystem.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/javax/sound/midi/MidiSystem.java	Sat Sep 25 12:00:05 2010 -0700
@@ -47,6 +47,8 @@
 import com.sun.media.sound.JDK13Services;
 import com.sun.media.sound.ReferenceCountingDevice;
 import com.sun.media.sound.AutoConnectSequencer;
+import com.sun.media.sound.MidiDeviceReceiverEnvelope;
+import com.sun.media.sound.MidiDeviceTransmitterEnvelope;
 
 
 /**
@@ -225,6 +227,8 @@
     /**
      * Obtains a MIDI receiver from an external MIDI port
      * or other default device.
+     * The returned receiver always implements
+     * the {@code MidiDeviceReceiver} interface.
      *
      * <p>If the system property
      * <code>javax.sound.midi.Receiver</code>
@@ -261,6 +265,9 @@
         } else {
             receiver = device.getReceiver();
         }
+        if (!(receiver instanceof MidiDeviceReceiver)) {
+            receiver = new MidiDeviceReceiverEnvelope(device, receiver);
+        }
         return receiver;
     }
 
@@ -268,6 +275,8 @@
     /**
      * Obtains a MIDI transmitter from an external MIDI port
      * or other default source.
+     * The returned transmitter always implements
+     * the {@code MidiDeviceTransmitter} interface.
      *
      * <p>If the system property
      * <code>javax.sound.midi.Transmitter</code>
@@ -301,6 +310,9 @@
         } else {
             transmitter = device.getTransmitter();
         }
+        if (!(transmitter instanceof MidiDeviceReceiver)) {
+            transmitter = new MidiDeviceTransmitterEnvelope(device, transmitter);
+        }
         return transmitter;
     }
 
--- a/src/share/classes/javax/sound/sampled/AudioFormat.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/javax/sound/sampled/AudioFormat.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -431,34 +431,36 @@
 
 
     /**
-     * Indicates whether this format matches the one specified.  To match,
-     * two formats must have the same encoding, the same number of channels,
-     * and the same number of bits per sample and bytes per frame.
-     * The two formats must also have the same sample rate,
-     * unless the specified format has the sample rate value <code>AudioSystem.NOT_SPECIFIED</code>,
-     * which any sample rate will match.  The frame rates must
-     * similarly be equal, unless the specified format has the frame rate
-     * value <code>AudioSystem.NOT_SPECIFIED</code>.  The byte order (big-endian or little-endian)
-     * must match if the sample size is greater than one byte.
+     * Indicates whether this format matches the one specified.
+     * To match, two formats must have the same encoding,
+     * and consistent values of the number of channels, sample rate, sample size,
+     * frame rate, and frame size.
+     * The values of the property are consistent if they are equal
+     * or the specified format has the property value
+     * {@code AudioSystem.NOT_SPECIFIED}.
+     * The byte order (big-endian or little-endian) must be the same
+     * if the sample size is greater than one byte.
      *
      * @param format format to test for match
-     * @return <code>true</code> if this format matches the one specified,
-     * <code>false</code> otherwise.
-     */
-    /*
-     * $$kk: 04.20.99: i changed the semantics of this.
+     * @return {@code true} if this format matches the one specified,
+     *         {@code false} otherwise.
      */
     public boolean matches(AudioFormat format) {
-
-        if (format.getEncoding().equals(getEncoding()) &&
-            ( (format.getSampleRate() == (float)AudioSystem.NOT_SPECIFIED) || (format.getSampleRate() == getSampleRate()) ) &&
-            (format.getSampleSizeInBits() == getSampleSizeInBits()) &&
-            (format.getChannels() == getChannels() &&
-             (format.getFrameSize() == getFrameSize()) &&
-             ( (format.getFrameRate() == (float)AudioSystem.NOT_SPECIFIED) || (format.getFrameRate() == getFrameRate()) ) &&
-             ( (format.getSampleSizeInBits() <= 8)  || (format.isBigEndian() == isBigEndian()) ) ) )
+        if (format.getEncoding().equals(getEncoding())
+                && (format.getChannels() == AudioSystem.NOT_SPECIFIED
+                    || format.getChannels() == getChannels())
+                && (format.getSampleRate() == (float)AudioSystem.NOT_SPECIFIED
+                    || format.getSampleRate() == getSampleRate())
+                && (format.getSampleSizeInBits() == AudioSystem.NOT_SPECIFIED
+                    || format.getSampleSizeInBits() == getSampleSizeInBits())
+                && (format.getFrameRate() == (float)AudioSystem.NOT_SPECIFIED
+                    || format.getFrameRate() == getFrameRate())
+                && (format.getFrameSize() == AudioSystem.NOT_SPECIFIED
+                    || format.getFrameSize() == getFrameSize())
+                && (getSampleSizeInBits() <= 8
+                    || format.isBigEndian() == isBigEndian())) {
             return true;
-
+        }
         return false;
     }
 
@@ -552,14 +554,14 @@
      * which is simply a linear (proportional) representation of the sound
      * waveform.  With PCM, the number stored in each sample is proportional
      * to the instantaneous amplitude of the sound pressure at that point in
-     * time.  The numbers are frequently signed or unsigned integers.
+     * time.  The numbers may be signed or unsigned integers or floats.
      * Besides PCM, other encodings include mu-law and a-law, which are nonlinear
      * mappings of the sound amplitude that are often used for recording speech.
      * <p>
      * You can use a predefined encoding by referring to one of the static
      * objects created by this class, such as PCM_SIGNED or
      * PCM_UNSIGNED.  Service providers can create new encodings, such as
-     * compressed audio formats or floating-point PCM samples, and make
+     * compressed audio formats, and make
      * these available through the <code>{@link AudioSystem}</code> class.
      * <p>
      * The <code>Encoding</code> class is static, so that all
@@ -590,6 +592,13 @@
         public static final Encoding PCM_UNSIGNED = new Encoding("PCM_UNSIGNED");
 
         /**
+         * Specifies floating-point PCM data.
+         *
+         * @since 1.7
+         */
+        public static final Encoding PCM_FLOAT = new Encoding("PCM_FLOAT");
+
+        /**
          * Specifies u-law encoded data.
          */
         public static final Encoding ULAW = new Encoding("ULAW");
--- a/src/share/classes/javax/swing/JColorChooser.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/javax/swing/JColorChooser.java	Sat Sep 25 12:00:05 2010 -0700
@@ -27,13 +27,11 @@
 
 import java.awt.*;
 import java.awt.event.*;
-import java.beans.*;
 import java.io.*;
 import java.util.*;
 
 import javax.swing.colorchooser.*;
 import javax.swing.plaf.ColorChooserUI;
-import javax.swing.event.*;
 import javax.accessibility.*;
 
 import sun.swing.SwingUtilities2;
@@ -95,7 +93,7 @@
 
     private ColorSelectionModel selectionModel;
 
-    private JComponent previewPanel;
+    private JComponent previewPanel = ColorChooserComponentFactory.getPreviewPanel();
 
     private AbstractColorChooserPanel[] chooserPanels = new AbstractColorChooserPanel[0];
 
--- a/src/share/classes/javax/swing/JDialog.java	Sat Sep 25 10:21:30 2010 +0800
+++ b/src/share/classes/javax/swing/JDialog.java	Sat Sep 25 12:00:05 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,12 +26,7 @@
 
 import java.awt.*;
 import java.awt.event.*;
-import java.beans.PropertyChangeListener;
-import java.util.Locale;
-import java.util.Vector;
-import java.io.Serializable;
 import javax.accessibility.*;
-import java.applet.Applet;
 
 /**
  * The main class for creating a dialog window. You can use this class
@@ -45,30 +40,30 @@
  *
  * <p>
  *
- * The <code>JDialog</code> component contains a <code>JRootPane</code>
+ * The {@code JDialog} component contains a {@code JRootPane}
  * as its only child.
- * The <code>contentPane</code> should be the parent of any children of the
- * <code>JDialog</code>.
- * As a convenience <code>add</code> and its variants, <code>remove</code> and
- * <code>setLayout</code> have been overridden to forward to the
- * <code>contentPane</code> as necessary. This means you can write:
+ * The {@code contentPane} should be the parent of any children of the
+ * {@code JDialog}.
+ * As a convenience {@code add} and its variants, {@code remove} and
+ * {@code setLayout} have been overridden to forward to the
+ * {@code contentPane} as necessary. This means you can write:
  * <pre>
  *       dialog.add(child);
  * </pre>
  * And the child will be added to the contentPane.
- * The <code>contentPane</code> is always non-<code>null</code>.
- * Attempting to set it to <code>null</code> generates an exception.
- * The default <code>contentPane</code> has a <code>BorderLayout</code>
+ * The {@code contentPane} is always non-{@code null}.
+ * Attempting to set it to {@code null} generates an exception.
+ * The default {@code contentPane} has a {@code BorderLayout}
  * manager set on it.
  * Refer to {@link javax.swing.RootPaneContainer}
- * for details on adding, removing and setting the <code>LayoutManager</code>
- * of a <code>JDialog</code>.
+ * for details on adding, removing and setting the {@code LayoutManager}
+ * of a {@code JDialog}.
  * <p>
- * Please see the <code>JRootPane</code> documentation for a complete
- * description of the <code>contentPane</code>, <code>glassPane</code>,
- * and <code>layeredPane</code> components.
+ * Please see the {@code JRootPane} documentation for a complete
+ * description of the {@code contentPane}, {@code glassPane},
+ * and {@code layeredPane} components.
  * <p>
- * In a multi-screen environment, you can create a <code>JDialog</code>
+ * In a multi-screen environment, you can create a {@code JDialog}
  * on a different screen device than its owner.  See {@link java.awt.Frame} for
  * more information.
  * <p>
@@ -83,7 +78,7 @@
  * appropriate for short term storage or RMI between applications running
  * the same version of Swing.  As of 1.4, support for long term storage
  * of all JavaBeans<sup><font size="-2">TM</font></sup>
- * has been added to the <code>java.beans</code> package.
+ * has been added to the {@code java.beans} package.
  * Please see {@link java.beans.XMLEncoder}.
  *
  * @see JOptionPane
@@ -120,9 +115,9 @@
     protected JRootPane rootPane;
 
     /**
-     * If true then calls to <code>add</code> and <code>setLayout</code>
-     * will be forwarded to the <code>contentPane</code>. This is initially
-     * false, but is set to true when the <code>JDialog</code> is constructed.
+     * If true then calls to {@code add} and {@code setLayout}
+     * will be forwarded to the {@code contentPane}. This is initially
+     * false, but is set to true when the {@code JDialog} is constructed.
      *
      * @see #isRootPaneCheckingEnabled
      * @see #setRootPaneCheckingEnabled
@@ -131,26 +126,26 @@
     protected boolean rootPaneCheckingEnabled = false;
 
     /**
-     * The <code>TransferHandler</code> for this dialog.
+     * The {@code TransferHandler} for this dialog.
      */
     private TransferHandler transferHandler;
 
     /**
      * Creates a modeless dialog without a title and without a specified
-     * <code>Frame</code> owner.  A shared, hidden frame will be
+     * {@code Frame} owner.  A shared, hidden frame will be
      * set as the owner of the dialog.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      * <p>
      * NOTE: This constructor does not allow you to create an unowned
-     * <code>JDialog</code>. To create an unowned <code>JDialog</code>
-     * you must use either the <code>JDialog(Window)</code> or
-     * <code>JDialog(Dialog)</code> constructor with an argument of
-     * <code>null</code>.
+     * {@code JDialog}. To create an unowned {@code JDialog}
+     * you must use either the {@code JDialog(Window)} or
+     * {@code JDialog(Dialog)} constructor with an argument of
+     * {@code null}.
      *
-     * @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      * @see java.awt.GraphicsEnvironment#isHeadless
      * @see JComponent#getDefaultLocale
      */
@@ -160,22 +155,22 @@
 
     /**
      * Creates a modeless dialog without a title with the
-     * specified <code>Frame</code> as its owner.  If <code>owner</code>
-     * is <code>null</code>, a shared, hidden frame will be set as the
+     * specified {@code Frame} as its owner.  If {@code owner}
+     * is {@code null}, a shared, hidden frame will be set as the
      * owner of the dialog.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      * <p>
      * NOTE: This constructor does not allow you to create an unowned
-     * <code>JDialog</code>. To create an unowned <code>JDialog</code>
-     * you must use either the <code>JDialog(Window)</code> or
-     * <code>JDialog(Dialog)</code> constructor with an argument of
-     * <code>null</code>.
+     * {@code JDialog}. To create an unowned {@code JDialog}
+     * you must use either the {@code JDialog(Window)} or
+     * {@code JDialog(Dialog)} constructor with an argument of
+     * {@code null}.
      *
-     * @param owner the <code>Frame</code> from which the dialog is displayed
-     * @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     * @param owner the {@code Frame} from which the dialog is displayed
+     * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      * @see java.awt.GraphicsEnvironment#isHeadless
      * @see JComponent#getDefaultLocale
      */
@@ -184,25 +179,25 @@
     }
 
     /**
-     * Creates a dialog with the specified owner <code>Frame</code>, modality
-     * and an empty title. If <code>owner</code> is <code>null</code>,
+     * Creates a dialog with the specified o