Merge
diff --git a/.hgtags b/.hgtags
index e12216b..90b30b8 100644
--- a/.hgtags
+++ b/.hgtags
@@ -98,3 +98,5 @@
 a661d8587b5d8986aacae086f5df66af9e1a96b1 jdk7-b121
 ac311eb325bfc763698219252bf3cee9e091f3af jdk7-b122
 869190935eedee7750d955019ab2a1b80f0a13a8 jdk7-b123
+1c72adc9d5f331cb882cf5354ba0dcb118a60b23 jdk7-b124
+0a56bdd709d01c1663047e55201d19152ffd3d69 jdk7-b125
diff --git a/make/common/shared/Defs-java.gmk b/make/common/shared/Defs-java.gmk
index c6026d9..7a58660 100644
--- a/make/common/shared/Defs-java.gmk
+++ b/make/common/shared/Defs-java.gmk
@@ -155,7 +155,7 @@
 		"-Xbootclasspath/p:$(JAVAC_JAR)" \
 		-jar $(JAVAC_JAR) $(JAVACFLAGS)
   JAVAH_CMD   = $(BOOT_JAVA_CMD) \
-		"-Xbootclasspath/p:$(JAVAH_JAR)$(CLASSPATH_SEPARATOR)$(JAVADOC_JAR)$(CLASSPATH_SEPARATOR)$(JAVAC_JAR)"  \
+		"-Xbootclasspath/p:$(JAVAH_JAR)$(CLASSPATH_SEPARATOR)$(JAVAC_JAR)"  \
 		-jar $(JAVAH_JAR) $(JAVAHFLAGS)
   JAVADOC_CMD = $(BOOT_JAVA_CMD) \
 		"-Xbootclasspath/p:$(JAVADOC_JAR)$(CLASSPATH_SEPARATOR)$(JAVAC_JAR)$(CLASSPATH_SEPARATOR)$(DOCLETS_JAR)" \
diff --git a/make/sun/awt/Makefile b/make/sun/awt/Makefile
index c7961dc..87fd56b 100644
--- a/make/sun/awt/Makefile
+++ b/make/sun/awt/Makefile
@@ -175,6 +175,10 @@
 include $(BUILDDIR)/common/Mapfile-vers.gmk
 include $(BUILDDIR)/common/Library.gmk
 
+COMPILEFONTCONFIG_FLAGS =
+ifdef ALT_COMPILEFONTCONFIG_FLAGS
+  COMPILEFONTCONFIG_FLAGS += $(ALT_COMPILEFONTCONFIG_FLAGS)
+endif
 build: fontconfigs
 
 
@@ -406,7 +410,7 @@
 $(LIBDIR)/%.bfc: $(FONTCONFIGS_SRC)/$(FONTCONFIGS_SRC_PREFIX)%.properties \
     $(COMPILEFONTCONFIG_JARFILE)
 	$(prep-target)
-	$(BOOT_JAVA_CMD) -jar $(COMPILEFONTCONFIG_JARFILE) $< $@
+	$(BOOT_JAVA_CMD) -jar $(COMPILEFONTCONFIG_JARFILE) $(COMPILEFONTCONFIG_FLAGS) $< $@
 	$(install-module-file)
 	$(call chmod-file, 444)
 	@$(java-vm-cleanup)
diff --git a/make/tools/src/build/tools/javazic/Zoneinfo.java b/make/tools/src/build/tools/javazic/Zoneinfo.java
index 143c687..872cc11 100644
--- a/make/tools/src/build/tools/javazic/Zoneinfo.java
+++ b/make/tools/src/build/tools/javazic/Zoneinfo.java
@@ -222,6 +222,7 @@
         boolean continued = false;
         Zone zone = null;
         String l;
+        lineNum = 0;
 
         try {
             while ((line = in.readLine()) != null) {
diff --git a/src/share/bin/java.c b/src/share/bin/java.c
index e02b8ac..2d1149c 100644
--- a/src/share/bin/java.c
+++ b/src/share/bin/java.c
@@ -158,8 +158,9 @@
  * Running Java code in primordial thread caused many problems. We will
  * create a new thread to invoke JVM. See 6316197 for more information.
  */
-static jlong threadStackSize = 0;  /* stack size of the new thread */
-static jlong heapSize        = 0;  /* heap size */
+static jlong threadStackSize    = 0;  /* stack size of the new thread */
+static jlong maxHeapSize        = 0;  /* max heap size */
+static jlong initialHeapSize    = 0;  /* inital heap size */
 
 int JNICALL JavaMain(void * args); /* entry point                  */
 
@@ -381,7 +382,7 @@
 
     if (showSettings != NULL) {
         ShowSettings(env, showSettings);
-        CHECK_EXCEPTION_LEAVE(0);
+        CHECK_EXCEPTION_LEAVE(1);
     }
     /* If the user specified neither a class name nor a JAR file */
     if (printXUsage || printUsage || (jarfile == 0 && classname == 0)) {
@@ -689,7 +690,14 @@
     if (JLI_StrCCmp(str, "-Xmx") == 0) {
         jlong tmp;
         if (parse_size(str + 4, &tmp)) {
-            heapSize = tmp;
+            maxHeapSize = tmp;
+        }
+    }
+
+    if (JLI_StrCCmp(str, "-Xms") == 0) {
+        jlong tmp;
+        if (parse_size(str + 4, &tmp)) {
+            initialHeapSize = tmp;
         }
     }
 }
@@ -1506,12 +1514,13 @@
     jstring joptString;
     NULL_CHECK(cls = FindBootStrapClass(env, "sun/launcher/LauncherHelper"));
     NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls,
-            "showSettings", "(ZLjava/lang/String;JJZ)V"));
+            "showSettings", "(ZLjava/lang/String;JJJZ)V"));
     joptString = (*env)->NewStringUTF(env, optString);
     (*env)->CallStaticVoidMethod(env, cls, showSettingsID,
                                  JNI_TRUE,
                                  joptString,
-                                 (jlong)heapSize,
+                                 (jlong)initialHeapSize,
+                                 (jlong)maxHeapSize,
                                  (jlong)threadStackSize,
                                  ServerClassMachine());
 }
diff --git a/src/share/classes/com/sun/java/util/jar/pack/AdaptiveCoding.java b/src/share/classes/com/sun/java/util/jar/pack/AdaptiveCoding.java
index 9fa3622..776a170 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/AdaptiveCoding.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/AdaptiveCoding.java
@@ -29,13 +29,14 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
+import static com.sun.java.util.jar.pack.Constants.*;
 
 /**
  * Adaptive coding.
  * See the section "Adaptive Encodings" in the Pack200 spec.
  * @author John Rose
  */
-class AdaptiveCoding implements Constants, CodingMethod {
+class AdaptiveCoding implements CodingMethod {
     CodingMethod headCoding;
     int          headLength;
     CodingMethod tailCoding;
@@ -147,7 +148,6 @@
         }
         if (KX == KX_MAX)  return Integer.MAX_VALUE;
         KX += 1;
-        int unit2 = 1      << (KX * KX_LG2BASE);
         int mask2 = KB_MAX << (KX * KX_LG2BASE);
         K1 |= (mask & ~mask2);
         K1 += unit;
@@ -250,7 +250,7 @@
         return m.toString();
     }
     public String toString() {
-        StringBuffer res = new StringBuffer(20);
+        StringBuilder res = new StringBuilder(20);
         AdaptiveCoding run = this;
         res.append("run(");
         for (;;) {
diff --git a/src/share/classes/com/sun/java/util/jar/pack/Attribute.java b/src/share/classes/com/sun/java/util/jar/pack/Attribute.java
index 7b838f2..f8d0e0c 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/Attribute.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/Attribute.java
@@ -36,6 +36,7 @@
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import static com.sun.java.util.jar.pack.Constants.*;
 
 /**
  * Represents an attribute in a class-file.
@@ -44,7 +45,7 @@
  * attribute layouts.
  * @author John Rose
  */
-class Attribute implements Comparable, Constants {
+class Attribute implements Comparable {
     // Attribute instance fields.
 
     Layout def;     // the name and format of this attr
@@ -103,7 +104,6 @@
         return this.def.compareTo(that.def);
     }
 
-    private static final byte[] noBytes = {};
     private static final Map<List<Attribute>, List<Attribute>> canonLists = new HashMap<>();
     private static final Map<Layout, Attribute> attributes = new HashMap<>();
     private static final Map<Layout, Attribute> standardDefs = new HashMap<>();
@@ -112,7 +112,7 @@
     // are used by trimToSize, in order to reduce footprint
     // of some common cases.  (Note that Code attributes are
     // always zero size.)
-    public static List getCanonList(List<Attribute> al) {
+    public static List<Attribute> getCanonList(List<Attribute> al) {
         synchronized (canonLists) {
             List<Attribute> cl = canonLists.get(al);
             if (cl == null) {
@@ -465,7 +465,9 @@
             return ConstantPool.getUtf8Entry(name());
         }
 
-        public boolean isEmpty() { return layout == ""; }
+        public boolean isEmpty() {
+            return layout.isEmpty();
+        }
 
         public Layout(int ctype, String name, String layout) {
             this.ctype = ctype;
@@ -479,19 +481,19 @@
                 } else {
                     String[] bodies = splitBodies(layout);
                     // Make the callables now, so they can be linked immediately.
-                    Element[] elems = new Element[bodies.length];
-                    this.elems = elems;
-                    for (int i = 0; i < elems.length; i++) {
+                    Element[] lelems = new Element[bodies.length];
+                    this.elems = lelems;
+                    for (int i = 0; i < lelems.length; i++) {
                         Element ce = this.new Element();
                         ce.kind = EK_CBLE;
                         ce.removeBand();
                         ce.bandIndex = NO_BAND_INDEX;
                         ce.layout = bodies[i];
-                        elems[i] = ce;
+                        lelems[i] = ce;
                     }
                     // Next fill them in.
-                    for (int i = 0; i < elems.length; i++) {
-                        Element ce = elems[i];
+                    for (int i = 0; i < lelems.length; i++) {
+                        Element ce = lelems[i];
                         ce.body = tokenizeLayout(this, i, bodies[i]);
                     }
                     //System.out.println(Arrays.asList(elems));
@@ -525,11 +527,12 @@
         }
 
         public boolean equals(Object x) {
-            return x instanceof Layout && equals((Layout)x);
+            return ( x != null) && ( x.getClass() == Layout.class ) &&
+                    equals((Layout)x);
         }
         public boolean equals(Layout that) {
-            return this.name == that.name
-                && this.layout == that.layout
+            return this.name.equals(that.name)
+                && this.layout.equals(that.layout)
                 && this.ctype == that.ctype;
         }
         public int hashCode() {
@@ -589,14 +592,14 @@
                 return str;
             }
             private String stringForDebug() {
-                Element[] body = this.body;
+                Element[] lbody = this.body;
                 switch (kind) {
                 case EK_CALL:
-                    body = null;
+                    lbody = null;
                     break;
                 case EK_CASE:
                     if (flagTest(EF_BACK))
-                        body = null;
+                        lbody = null;
                     break;
                 }
                 return layout
@@ -604,7 +607,7 @@
                     + "<"+ (flags==0?"":""+flags)+kind+len
                     + (refKind==0?"":""+refKind) + ">"
                     + (value==0?"":"("+value+")")
-                    + (body==null?"": ""+Arrays.asList(body));
+                    + (lbody==null?"": ""+Arrays.asList(lbody));
             }
         }
 
@@ -613,16 +616,19 @@
         }
         static private final Element[] noElems = {};
         public Element[] getCallables() {
-            if (hasCallables())
-                return elems;
-            else
+            if (hasCallables()) {
+                Element[] nelems = Arrays.copyOf(elems, elems.length);
+                return nelems;
+            } else
                 return noElems;  // no callables at all
         }
         public Element[] getEntryPoint() {
             if (hasCallables())
                 return elems[0].body;  // body of first callable
-            else
-                return elems;  // no callables; whole body
+            else {
+                Element[] nelems = Arrays.copyOf(elems, elems.length);
+                return nelems;  // no callables; whole body
+            }
         }
 
         /** Return a sequence of tokens from the given attribute bytes.
@@ -674,7 +680,7 @@
         }
     }
 
-    void visitRefs(Holder holder, int mode, final Collection refs) {
+    void visitRefs(Holder holder, int mode, final Collection<Entry> refs) {
         if (mode == VRM_CLASSIC) {
             refs.add(getNameRef());
         }
@@ -720,7 +726,7 @@
      */
     static public
     String normalizeLayoutString(String layout) {
-        StringBuffer buf = new StringBuffer();
+        StringBuilder buf = new StringBuilder();
         for (int i = 0, len = layout.length(); i < len; ) {
             char ch = layout.charAt(i++);
             if (ch <= ' ') {
@@ -832,14 +838,14 @@
     */
     static //private
     Layout.Element[] tokenizeLayout(Layout self, int curCble, String layout) {
-        ArrayList<Layout.Element> col = new ArrayList<>(layout.length());
+        List<Layout.Element> col = new ArrayList<>(layout.length());
         tokenizeLayout(self, curCble, layout, col);
         Layout.Element[] res = new Layout.Element[col.size()];
         col.toArray(res);
         return res;
     }
     static //private
-    void tokenizeLayout(Layout self, int curCble, String layout, ArrayList<Layout.Element> col) {
+    void tokenizeLayout(Layout self, int curCble, String layout, List<Layout.Element> col) {
         boolean prevBCI = false;
         for (int len = layout.length(), i = 0; i < len; ) {
             int start = i;
@@ -897,7 +903,7 @@
             case 'T': // union: 'T' any_int union_case* '(' ')' '[' body ']'
                 kind = EK_UN;
                 i = tokenizeSInt(e, layout, i);
-                ArrayList<Layout.Element> cases = new ArrayList<>();
+                List<Layout.Element> cases = new ArrayList<>();
                 for (;;) {
                     // Keep parsing cases until we hit the default case.
                     if (layout.charAt(i++) != '(')
@@ -1051,7 +1057,7 @@
     }
     static //private
     String[] splitBodies(String layout) {
-        ArrayList<String> bodies = new ArrayList<>();
+        List<String> bodies = new ArrayList<>();
         // Parse several independent layout bodies:  "[foo][bar]...[baz]"
         for (int i = 0; i < layout.length(); i++) {
             if (layout.charAt(i++) != '[')
@@ -1156,7 +1162,7 @@
     String expandCaseDashNotation(String layout) {
         int dash = findCaseDash(layout, 0);
         if (dash < 0)  return layout;  // no dashes (the common case)
-        StringBuffer result = new StringBuffer(layout.length() * 3);
+        StringBuilder result = new StringBuilder(layout.length() * 3);
         int sofar = 0;  // how far have we processed the layout?
         for (;;) {
             // for each dash, collect everything up to the dash
diff --git a/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java b/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java
index 62c4dd2..3a154a0 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java
@@ -44,16 +44,17 @@
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 import java.util.jar.Pack200;
+import static com.sun.java.util.jar.pack.Constants.*;
 
 /**
  * Define the structure and ordering of "bands" in a packed file.
  * @author John Rose
  */
 abstract
-class BandStructure implements Constants {
+class BandStructure {
     static final int MAX_EFFORT = 9;
     static final int MIN_EFFORT = 1;
     static final int DEFAULT_EFFORT = 5;
@@ -251,18 +252,18 @@
 
         null
     };
-    final private static HashMap basicCodingIndexes;
+    final private static Map<Coding, Integer> basicCodingIndexes;
     static {
         assert(basicCodings[_meta_default] == null);
         assert(basicCodings[_meta_canon_min] != null);
         assert(basicCodings[_meta_canon_max] != null);
-        HashMap map = new HashMap();
+        Map<Coding, Integer> map = new HashMap<>();
         for (int i = 0; i < basicCodings.length; i++) {
             Coding c = basicCodings[i];
             if (c == null)  continue;
             assert(i >= _meta_canon_min);
             assert(i <= _meta_canon_max);
-            map.put(c, new Integer(i));
+            map.put(c, i);
         }
         basicCodingIndexes = map;
     }
@@ -270,12 +271,12 @@
         return i < basicCodings.length ? basicCodings[i] : null;
     }
     public static int indexOf(Coding c) {
-        Integer i = (Integer) basicCodingIndexes.get(c);
+        Integer i = basicCodingIndexes.get(c);
         if (i == null)  return 0;
         return i.intValue();
     }
     public static Coding[] getBasicCodings() {
-        return (Coding[]) basicCodings.clone();
+        return basicCodings.clone();
     }
 
     protected byte[] bandHeaderBytes;    // used for input only
@@ -687,7 +688,6 @@
             }
             bandCoding.writeArrayTo(out, values, 0, length);
             if (out == outputCounter) {
-                long len1 = outputCounter.getCount();
                 assert(outputSize == outputCounter.getCount() - len0)
                     : (outputSize+" != "+outputCounter.getCount()+"-"+len0);
             }
@@ -1050,8 +1050,8 @@
 
     // Bootstrap support for CPRefBands.  These are needed to record
     // intended CP indexes, before the CP has been created.
-    private ArrayList allKQBands = new ArrayList();
-    private ArrayList needPredefIndex = new ArrayList();
+    private final List<CPRefBand> allKQBands = new ArrayList<>();
+    private List<Object[]> needPredefIndex = new ArrayList<>();
 
 
     int encodeRef(Entry e, Index ix) {
@@ -1078,9 +1078,9 @@
                 && this instanceof PackageWriter) {
                 // Twist the random state based on my first file.
                 // This sends each segment off in a different direction.
-                List classes = ((PackageWriter)this).pkg.classes;
+                List<Package.Class> classes = ((PackageWriter)this).pkg.classes;
                 if (!classes.isEmpty()) {
-                    Package.Class cls = (Package.Class) classes.get(0);
+                    Package.Class cls = classes.get(0);
                     codingChooser.addStressSeed(cls.getName().hashCode());
                 }
             }
@@ -1619,8 +1619,7 @@
     /** Given CP indexes, distribute tag-specific indexes to bands. */
     protected void setBandIndexes() {
         // Handle prior calls to setBandIndex:
-        for (Iterator i = needPredefIndex.iterator(); i.hasNext(); ) {
-            Object[] need = (Object[]) i.next();
+        for (Object[] need : needPredefIndex) {
             CPRefBand b     = (CPRefBand) need[0];
             Byte      which = (Byte)      need[1];
             b.setIndex(getCPIndex(which.byteValue()));
@@ -1633,7 +1632,7 @@
     }
 
     protected void setBandIndex(CPRefBand b, byte which) {
-        Object[] need = { b, new Byte(which) };
+        Object[] need = { b, Byte.valueOf(which) };
         if (which == CONSTANT_Literal) {
             // I.e., attribute layouts KQ (no null) or KQN (null ok).
             allKQBands.add(b);
@@ -1645,7 +1644,7 @@
         }
     }
 
-    protected void setConstantValueIndex(com.sun.java.util.jar.pack.Package.Class.Field f) {
+    protected void setConstantValueIndex(Field f) {
         Index ix = null;
         if (f != null) {
             byte tag = f.getLiteralTag();
@@ -1655,8 +1654,7 @@
             assert(ix != null);
         }
         // Typically, allKQBands is the singleton of field_ConstantValue_KQ.
-        for (Iterator i = allKQBands.iterator(); i.hasNext(); ) {
-            CPRefBand xxx_KQ = (CPRefBand) i.next();
+        for (CPRefBand xxx_KQ : allKQBands) {
             xxx_KQ.setIndex(ix);
         }
     }
@@ -1688,7 +1686,7 @@
     protected int attrClassFileVersionMask;
 
     // Mapping from Attribute.Layout to Band[] (layout element bands).
-    protected HashMap attrBandTable = new HashMap();
+    protected Map<Attribute.Layout, Band[]> attrBandTable = new HashMap<>();
 
     // Well-known attributes:
     protected final Attribute.Layout attrCodeEmpty;
@@ -1697,15 +1695,18 @@
     protected final Attribute.Layout attrConstantValue;
 
     // Mapping from Attribute.Layout to Integer (inverse of attrDefs)
-    HashMap attrIndexTable = new HashMap();
+    Map<Attribute.Layout, Integer> attrIndexTable = new HashMap<>();
 
     // Mapping from attribute index (<32 are flag bits) to attributes.
-    protected ArrayList[] attrDefs = new ArrayList[ATTR_CONTEXT_LIMIT];
+    protected List<List<Attribute.Layout>> attrDefs =
+            new FixedList<>(ATTR_CONTEXT_LIMIT);
     {
         for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
             assert(attrIndexLimit[i] == 0);
             attrIndexLimit[i] = 32;  // just for the sake of predefs.
-            attrDefs[i] = new ArrayList(Collections.nCopies(attrIndexLimit[i], null));
+            attrDefs.set(i, new ArrayList<>(Collections.nCopies(
+                    attrIndexLimit[i], (Attribute.Layout)null)));
+
         }
 
         // Add predefined attribute definitions:
@@ -1867,9 +1868,10 @@
         for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
             assert(attrIndexLimit[i] == 0);  // decide on it now!
             attrIndexLimit[i] = (haveFlagsHi(i)? 63: 32);
-            assert(attrDefs[i].size() == 32);  // all predef indexes are <32
-            int addMore = attrIndexLimit[i] - attrDefs[i].size();
-            attrDefs[i].addAll(Collections.nCopies(addMore, null));
+            List<Attribute.Layout> defList = attrDefs.get(i);
+            assert(defList.size() == 32);  // all predef indexes are <32
+            int addMore = attrIndexLimit[i] - defList.size();
+            defList.addAll(Collections.nCopies(addMore, (Attribute.Layout) null));
         }
     }
 
@@ -1890,13 +1892,13 @@
         return testBit(archiveOptions, mask);
     }
 
-    protected ArrayList getPredefinedAttrs(int ctype) {
+    protected List getPredefinedAttrs(int ctype) {
         assert(attrIndexLimit[ctype] != 0);
-        ArrayList res = new ArrayList(attrIndexLimit[ctype]);
+        List<Attribute.Layout> res = new ArrayList<>(attrIndexLimit[ctype]);
         // Remove nulls and non-predefs.
         for (int ai = 0; ai < attrIndexLimit[ctype]; ai++) {
             if (testBit(attrDefSeen[ctype], 1L<<ai))  continue;
-            Attribute.Layout def = (Attribute.Layout) attrDefs[ctype].get(ai);
+            Attribute.Layout def = attrDefs.get(ctype).get(ai);
             if (def == null)  continue;  // unused flag bit
             assert(isPredefinedAttr(ctype, ai));
             res.add(def);
@@ -1910,7 +1912,7 @@
         if (ai >= attrIndexLimit[ctype])          return false;
         // If the bit is set, it was explicitly def'd.
         if (testBit(attrDefSeen[ctype], 1L<<ai))  return false;
-        return (attrDefs[ctype].get(ai) != null);
+        return (attrDefs.get(ctype).get(ai) != null);
     }
 
     protected void adjustSpecialAttrMasks() {
@@ -2050,8 +2052,8 @@
             System.out.println("Removing predefined "+ATTR_CONTEXT_NAME[ctype]+
                                " attribute on bit "+index);
         }
-        List defList = attrDefs[ctype];
-        Attribute.Layout def = (Attribute.Layout) defList.get(index);
+        List<Attribute.Layout> defList = attrDefs.get(ctype);
+        Attribute.Layout def = defList.get(index);
         assert(def != null);
         defList.set(index, null);
         attrIndexTable.put(def, null);
@@ -2059,7 +2061,7 @@
         assert(index < 64);
         attrDefSeen[ctype]  &= ~(1L<<index);
         attrFlagMask[ctype] &= ~(1L<<index);
-        Band[] ab = (Band[]) attrBandTable.get(def);
+        Band[] ab = attrBandTable.get(def);
         for (int j = 0; j < ab.length; j++) {
             ab[j].doneWithUnusedBand();
         }
@@ -2085,9 +2087,8 @@
             long defSeen = attrDefSeen[ctype];
             // Note: attrDefSeen is always a subset of attrFlagMask.
             assert((defSeen & ~attrFlagMask[ctype]) == 0);
-            for (int i = 0; i < attrDefs[ctype].size(); i++) {
-                Attribute.Layout def = (Attribute.Layout)
-                    attrDefs[ctype].get(i);
+            for (int i = 0; i < attrDefs.get(ctype).size(); i++) {
+                Attribute.Layout def = attrDefs.get(ctype).get(i);
                 if (def == null)  continue;  // unused flag bit
                 if (def.bandCount == 0)  continue;  // empty attr
                 if (i < attrIndexLimit[ctype] && !testBit(defSeen, 1L<<i)) {
@@ -2102,7 +2103,7 @@
                 Band[] newAB  = makeNewAttributeBands(pfx, def,
                                                       xxx_attr_bands);
                 assert(newAB.length == def.bandCount);
-                Band[] prevAB = (Band[]) attrBandTable.put(def, newAB);
+                Band[] prevAB = attrBandTable.put(def, newAB);
                 if (prevAB != null) {
                     // We won't be using these predefined bands.
                     for (int j = 0; j < prevAB.length; j++) {
@@ -2212,14 +2213,14 @@
     protected int setAttributeLayoutIndex(Attribute.Layout def, int index) {
         int ctype = def.ctype;
         assert(ATTR_INDEX_OVERFLOW <= index && index < attrIndexLimit[ctype]);
-        List defList = attrDefs[ctype];
+        List<Attribute.Layout> defList = attrDefs.get(ctype);
         if (index == ATTR_INDEX_OVERFLOW) {
             // Overflow attribute.
             index = defList.size();
             defList.add(def);
             if (verbose > 0)
                 Utils.log.info("Adding new attribute at "+def +": "+index);
-            attrIndexTable.put(def, new Integer(index));
+            attrIndexTable.put(def, index);
             return index;
         }
 
@@ -2240,7 +2241,7 @@
         // Remove index binding of any previous fixed attr.
         attrIndexTable.put(defList.get(index), null);
         defList.set(index, def);
-        attrIndexTable.put(def, new Integer(index));
+        attrIndexTable.put(def, index);
         return index;
     }
 
@@ -2361,7 +2362,7 @@
     ////////////////////////////////////////////////////////////////////
 
     static int nextSeqForDebug;
-    static File dumpDir;
+    static File dumpDir = null;
     static OutputStream getDumpStream(Band b, String ext) throws IOException {
         return getDumpStream(b.name, b.seqForDebug, ext, b);
     }
@@ -2512,19 +2513,19 @@
                            +", "+cstr+", "+ixS+"),");
     }
 
-    private HashMap prevForAssertMap;
+    private Map<Band, Band> prevForAssertMap;
 
     // DEBUG ONLY:  Record something about the band order.
     boolean notePrevForAssert(Band b, Band p) {
         if (prevForAssertMap == null)
-            prevForAssertMap = new HashMap();
+            prevForAssertMap = new HashMap<>();
         prevForAssertMap.put(b, p);
         return true;
     }
 
     // DEBUG ONLY:  Validate next input band.
     private boolean assertReadyToReadFrom(Band b, InputStream in) throws IOException {
-        Band p = (Band) prevForAssertMap.get(b);
+        Band p = prevForAssertMap.get(b);
         // Any previous band must be done reading before this one starts.
         if (p != null && phaseCmp(p.phase(), DISBURSE_PHASE) < 0) {
             Utils.log.warning("Previous band not done reading.");
@@ -2536,19 +2537,21 @@
         String name = b.name;
         if (optDebugBands && !name.startsWith("(")) {
             // Verify synchronization between reader & writer:
-            StringBuffer buf = new StringBuffer();
+            StringBuilder buf = new StringBuilder();
             int ch;
             while ((ch = in.read()) > 0)
                 buf.append((char)ch);
             String inName = buf.toString();
             if (!inName.equals(name)) {
-                StringBuffer sb = new StringBuffer();
+                StringBuilder sb = new StringBuilder();
                 sb.append("Expected "+name+" but read: ");
                 inName += (char)ch;
-                while (inName.length() < 10)
-                    inName += (char)in.read();
-                for (int i = 0; i < inName.length(); i++)
+                while (inName.length() < 10) {
+                    inName += (char) in.read();
+                }
+                for (int i = 0; i < inName.length(); i++) {
                     sb.append(inName.charAt(i));
+                }
                 Utils.log.warning(sb.toString());
                 return false;
             }
@@ -2573,7 +2576,7 @@
 
     // DEBUG ONLY:  Maybe write a debugging cookie to next output band.
     private boolean assertReadyToWriteTo(Band b, OutputStream out) throws IOException {
-        Band p = (Band) prevForAssertMap.get(b);
+        Band p = prevForAssertMap.get(b);
         // Any previous band must be done writing before this one starts.
         if (p != null && phaseCmp(p.phase(), DONE_PHASE) < 0) {
             Utils.log.warning("Previous band not done writing.");
@@ -2654,7 +2657,7 @@
     protected static Object[] realloc(Object[] a) {
         return realloc(a, Math.max(10, a.length*2));
     }
-    static private int[] noInts = {};
+
     protected static int[] realloc(int[] a, int len) {
         if (len == 0)  return noInts;
         if (a == null)  return new int[len];
@@ -2665,7 +2668,7 @@
     protected static int[] realloc(int[] a) {
         return realloc(a, Math.max(10, a.length*2));
     }
-    static private byte[] noBytes = {};
+
     protected static byte[] realloc(byte[] a, int len) {
         if (len == 0)  return noBytes;
         if (a == null)  return new byte[len];
diff --git a/src/share/classes/com/sun/java/util/jar/pack/ClassReader.java b/src/share/classes/com/sun/java/util/jar/pack/ClassReader.java
index a1bce52..eef5d20 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/ClassReader.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/ClassReader.java
@@ -38,19 +38,20 @@
 import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.Map;
+import static com.sun.java.util.jar.pack.Constants.*;
 
 /**
  * Reader for a class file that is being incorporated into a package.
  * @author John Rose
  */
-class ClassReader implements Constants {
+class ClassReader {
     int verbose;
 
     Package pkg;
     Class cls;
     long inPos;
     DataInputStream in;
-    Map attrDefs;
+    Map<Attribute.Layout, Attribute> attrDefs;
     Map attrCommands;
     String unknownAttrCommand = "error";;
 
@@ -77,7 +78,7 @@
         });
     }
 
-    public void setAttrDefs(Map attrDefs) {
+    public void setAttrDefs(Map<Attribute.Layout, Attribute> attrDefs) {
         this.attrDefs = attrDefs;
     }
 
@@ -211,27 +212,23 @@
                     break;
                 case CONSTANT_Integer:
                     {
-                        Comparable val = new Integer(in.readInt());
-                        cpMap[i] = ConstantPool.getLiteralEntry(val);
+                        cpMap[i] = ConstantPool.getLiteralEntry(in.readInt());
                     }
                     break;
                 case CONSTANT_Float:
                     {
-                        Comparable val = new Float(in.readFloat());
-                        cpMap[i] = ConstantPool.getLiteralEntry(val);
+                        cpMap[i] = ConstantPool.getLiteralEntry(in.readFloat());
                     }
                     break;
                 case CONSTANT_Long:
                     {
-                        Comparable val = new Long(in.readLong());
-                        cpMap[i] = ConstantPool.getLiteralEntry(val);
+                        cpMap[i] = ConstantPool.getLiteralEntry(in.readLong());
                         cpMap[++i] = null;
                     }
                     break;
                 case CONSTANT_Double:
                     {
-                        Comparable val = new Double(in.readDouble());
-                        cpMap[i] = ConstantPool.getLiteralEntry(val);
+                        cpMap[i] = ConstantPool.getLiteralEntry(in.readDouble());
                         cpMap[++i] = null;
                     }
                     break;
@@ -353,17 +350,18 @@
             if (attrCommands != null) {
                 Object lkey = Attribute.keyForLookup(ctype, name);
                 String cmd = (String) attrCommands.get(lkey);
-                if (cmd == "pass") {
-                    String message = "passing attribute bitwise in "+h;
-                    throw new Attribute.FormatException(message, ctype, name,
-                                                        cmd);
-                } else if (cmd == "error") {
-                    String message = "attribute not allowed in "+h;
-                    throw new Attribute.FormatException(message, ctype, name,
-                                                        cmd);
-                } else if (cmd == "strip") {
-                    skip(length, name+" attribute in "+h);
-                    continue;
+                if (cmd != null) {
+                    switch (cmd) {
+                        case "pass":
+                            String message1 = "passing attribute bitwise in " + h;
+                            throw new Attribute.FormatException(message1, ctype, name, cmd);
+                        case "error":
+                            String message2 = "attribute not allowed in " + h;
+                            throw new Attribute.FormatException(message2, ctype, name, cmd);
+                        case "strip":
+                            skip(length, name + " attribute in " + h);
+                            continue;
+                    }
                 }
             }
             // Find canonical instance of the requested attribute.
@@ -408,7 +406,7 @@
                     String message = "unsupported StackMap variant in "+h;
                     throw new Attribute.FormatException(message, ctype, name,
                                                         "pass");
-                } else if (unknownAttrCommand == "strip") {
+                } else if ("strip".equals(unknownAttrCommand)) {
                     // Skip the unknown attribute.
                     skip(length, "unknown "+name+" attribute in "+h);
                     continue;
@@ -422,7 +420,7 @@
                 a.layout() == Package.attrInnerClassesEmpty) {
                 // These are hardwired.
                 long pos0 = inPos;
-                if (a.name() == "Code") {
+                if ("Code".equals(a.name())) {
                     Class.Method m = (Class.Method) h;
                     m.code = new Code(m);
                     try {
@@ -471,7 +469,7 @@
 
     void readInnerClasses(Class cls) throws IOException {
         int nc = readUnsignedShort();
-        ArrayList ics = new ArrayList(nc);
+        ArrayList<InnerClass> ics = new ArrayList<>(nc);
         for (int i = 0; i < nc; i++) {
             InnerClass ic =
                 new InnerClass(readClassRef(),
diff --git a/src/share/classes/com/sun/java/util/jar/pack/ClassWriter.java b/src/share/classes/com/sun/java/util/jar/pack/ClassWriter.java
index b9862b5..c8c5414 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/ClassWriter.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/ClassWriter.java
@@ -38,12 +38,12 @@
 import java.io.OutputStream;
 import java.util.Iterator;
 import java.util.List;
-
+import static com.sun.java.util.jar.pack.Constants.*;
 /**
  * Writer for a class file that is incorporated into a package.
  * @author John Rose
  */
-class ClassWriter implements Constants {
+class ClassWriter {
     int verbose;
 
     Package pkg;
@@ -196,8 +196,7 @@
             return;
         }
         writeShort(h.attributes.size());
-        for (Iterator i = h.attributes.iterator(); i.hasNext(); ) {
-            Attribute a = (Attribute) i.next();
+        for (Attribute a : h.attributes) {
             a.finishRefs(cpIndex);
             writeRef(a.getNameRef());
             if (a.layout() == Package.attrCodeEmpty ||
@@ -207,7 +206,7 @@
                 assert(out != bufOut);
                 buf.reset();
                 out = bufOut;
-                if (a.name() == "Code") {
+                if ("Code".equals(a.name())) {
                     Class.Method m = (Class.Method) h;
                     writeCode(m.code);
                 } else {
@@ -246,10 +245,9 @@
     }
 
     void writeInnerClasses(Class cls) throws IOException {
-        List ics = cls.getInnerClasses();
+        List<InnerClass> ics = cls.getInnerClasses();
         writeShort(ics.size());
-        for (Iterator i = ics.iterator(); i.hasNext(); ) {
-            InnerClass ic = (InnerClass) i.next();
+        for (InnerClass ic : ics) {
             writeRef(ic.thisClass);
             writeRef(ic.outerClass);
             writeRef(ic.name);
diff --git a/src/share/classes/com/sun/java/util/jar/pack/Code.java b/src/share/classes/com/sun/java/util/jar/pack/Code.java
index 56bcbe0..788eada 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/Code.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/Code.java
@@ -29,12 +29,13 @@
 import java.lang.reflect.Modifier;
 import java.util.Arrays;
 import java.util.Collection;
+import static com.sun.java.util.jar.pack.Constants.*;
 
 /**
  * Represents a chunk of bytecodes.
  * @author John Rose
  */
-class Code extends Attribute.Holder implements Constants {
+class Code extends Attribute.Holder {
     Class.Method m;
 
     public Code(Class.Method m) {
@@ -141,15 +142,12 @@
         super.trimToSize();
     }
 
-    protected void visitRefs(int mode, Collection refs) {
+    protected void visitRefs(int mode, Collection<ConstantPool.Entry> refs) {
         int verbose = getPackage().verbose;
         if (verbose > 2)
             System.out.println("Reference scan "+this);
         Class cls = thisClass();
-        Package pkg = cls.getPackage();
-        for (int i = 0; i < handler_class.length; i++) {
-            refs.add(handler_class[i]);
-        }
+        refs.addAll(Arrays.asList(handler_class));
         if (fixups != null) {
             fixups.visitRefs(refs);
         } else {
@@ -196,11 +194,8 @@
             map[mapLen] = (short)(PClimit + Short.MIN_VALUE);
             return map;
         } else {
-            int[] map = new int[mapLen+1];
-            for (int i = 0; i < mapLen; i++) {
-                map[i] = (int) insnMap[i];
-            }
-            map[mapLen] = (int) PClimit;
+            int[] map = Arrays.copyOf(insnMap, mapLen + 1);
+            map[mapLen] = PClimit;
             return map;
         }
     }
@@ -220,10 +215,7 @@
             }
         } else {
             int[] map = (int[]) map0;
-            imap = new int[map.length-1];
-            for (int i = 0; i < imap.length; i++) {
-                imap[i] = map[i];
-            }
+            imap = Arrays.copyOfRange(map, 0, map.length - 1);
         }
         return imap;
     }
@@ -266,7 +258,7 @@
         } else {
             int[] map = (int[]) map0;
             len = map.length;
-            i = Arrays.binarySearch(map, (int)bci);
+            i = Arrays.binarySearch(map, bci);
         }
         assert(i != -1);
         assert(i != 0);
@@ -322,7 +314,7 @@
             len = map.length;
             if (bciCode < len)
                 return map[bciCode];
-            i = Arrays.binarySearch(map, (int)bciCode);
+            i = Arrays.binarySearch(map, bciCode);
             if (i < 0)  i = -i-1;
             int key = bciCode-len;
             for (;; i--) {
diff --git a/src/share/classes/com/sun/java/util/jar/pack/Coding.java b/src/share/classes/com/sun/java/util/jar/pack/Coding.java
index 4667305..2f73b8e 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/Coding.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/Coding.java
@@ -29,14 +29,15 @@
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.util.HashMap;
-
+import java.util.Map;
+import static com.sun.java.util.jar.pack.Constants.*;
 /**
  * Define the conversions between sequences of small integers and raw bytes.
  * This is a schema of encodings which incorporates varying lengths,
  * varying degrees of length variability, and varying amounts of signed-ness.
  * @author John Rose
  */
-class Coding implements Constants, Comparable, CodingMethod, Histogram.BitMetric {
+class Coding implements Comparable, CodingMethod, Histogram.BitMetric {
     /*
       Coding schema for single integers, parameterized by (B,H,S):
 
@@ -191,7 +192,9 @@
         if (S == 0 || range >= (long)1<<32)
             return saturate32(range-1);
         long maxPos = range-1;
-        while (isNegativeCode(maxPos, S))  --maxPos;
+        while (isNegativeCode(maxPos, S)) {
+            --maxPos;
+        }
         if (maxPos < 0)  return -1;  // No positive codings at all.
         int smax = decodeSign32(maxPos, S);
         // check for 32-bit wraparound:
@@ -213,9 +216,10 @@
         if (S == 0) {
             return 0;
         }
-        int Smask = (1<<S)-1;
         long maxNeg = range-1;
-        while (!isNegativeCode(maxNeg, S))  --maxNeg;
+        while (!isNegativeCode(maxNeg, S))
+            --maxNeg;
+
         if (maxNeg < 0)  return 0;  // No negative codings at all.
         return decodeSign32(maxNeg, S);
     }
@@ -395,12 +399,12 @@
         return (del<<14)+(S<<11)+(B<<8)+(H<<0);
     }
 
-    private static HashMap codeMap;
+    private static Map<Coding, Coding> codeMap;
 
     private static synchronized Coding of(int B, int H, int S, int del) {
-        if (codeMap == null)  codeMap = new HashMap();
+        if (codeMap == null)  codeMap = new HashMap<>();
         Coding x0 = new Coding(B, H, S, del);
-        Coding x1 = (Coding) codeMap.get(x0);
+        Coding x1 = codeMap.get(x0);
         if (x1 == null)  codeMap.put(x0, x1 = x0);
         return x1;
     }
@@ -462,6 +466,7 @@
         // %%% use byte[] buffer
         for (int i = start; i < end; i++)
             a[i] = readFrom(in);
+
         for (int dstep = 0; dstep < del; dstep++) {
             long state = 0;
             for (int i = start; i < end; i++) {
@@ -750,14 +755,14 @@
         if (len == 0)       return true;
         if (isFullRange())  return true;
         // Calculate max, min:
-        int max = values[start];
-        int min = max;
+        int lmax = values[start];
+        int lmin = lmax;
         for (int i = 1; i < len; i++) {
             int value = values[start+i];
-            if (max < value)  max = value;
-            if (min > value)  min = value;
+            if (lmax < value)  lmax = value;
+            if (lmin > value)  lmin = value;
         }
-        return canRepresent(min, max);
+        return canRepresent(lmin, lmax);
     }
 
     public double getBitLength(int value) {  // implements BitMetric
@@ -800,21 +805,20 @@
             //return Coding.of(B, H, S).getLength(deltas, 0, len);
             values = deltas;
             start = 0;
-            end = values.length;
         }
         int sum = len;  // at least 1 byte per
         // add extra bytes for extra-long values
         for (int n = 1; n <= B; n++) {
             // what is the coding interval [min..max] for n bytes?
-            int max = byteMax[n-1];
-            int min = byteMin[n-1];
+            int lmax = byteMax[n-1];
+            int lmin = byteMin[n-1];
             int longer = 0;  // count of guys longer than n bytes
             for (int i = 0; i < len; i++) {
                 int value = values[start+i];
                 if (value >= 0) {
-                    if (value > max)  longer++;
+                    if (value > lmax)  longer++;
                 } else {
-                    if (value < min)  longer++;
+                    if (value < lmin)  longer++;
                 }
             }
             if (longer == 0)  break;  // no more passes needed
diff --git a/src/share/classes/com/sun/java/util/jar/pack/CodingChooser.java b/src/share/classes/com/sun/java/util/jar/pack/CodingChooser.java
index 38ff748..f173cf8 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/CodingChooser.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/CodingChooser.java
@@ -34,15 +34,16 @@
 import java.util.Iterator;
 import java.util.List;
 import java.util.Random;
+import java.util.Set;
 import java.util.zip.Deflater;
 import java.util.zip.DeflaterOutputStream;
-
+import static com.sun.java.util.jar.pack.Constants.*;
 /**
  * Heuristic chooser of basic encodings.
  * Runs "zip" to measure the apparent information content after coding.
  * @author John Rose
  */
-class CodingChooser implements Constants {
+class CodingChooser {
     int verbose;
     int effort;
     boolean optUseHistogram = true;
@@ -124,10 +125,10 @@
                 = !p200.getBoolean(Utils.COM_PREFIX+"no.population.coding");
             this.optUseAdaptiveCoding
                 = !p200.getBoolean(Utils.COM_PREFIX+"no.adaptive.coding");
-            int stress
+            int lstress
                 = p200.getInteger(Utils.COM_PREFIX+"stress.coding");
-            if (stress != 0)
-                this.stress = new Random(stress);
+            if (lstress != 0)
+                this.stress = new Random(lstress);
         }
 
         this.effort = effort;
@@ -376,9 +377,9 @@
                              " fewer bytes than regular "+regular+
                              "; win="+pct(zipSize1-bestZipSize, zipSize1));
         }
-        CodingMethod bestMethod = this.bestMethod;
+        CodingMethod lbestMethod = this.bestMethod;
         reset(null, 0, 0);  // for GC
-        return bestMethod;
+        return lbestMethod;
     }
     CodingMethod choose(int[] values, int start, int end, Coding regular) {
         return choose(values, start, end, regular, null);
@@ -742,9 +743,9 @@
         // Steps 1/2/3 are interdependent, and may be iterated.
         // Steps 4 and 5 may be decided independently afterward.
         int[] LValuesCoded = PopulationCoding.LValuesCoded;
-        ArrayList bestFits = new ArrayList();
-        ArrayList fullFits = new ArrayList();
-        ArrayList longFits = new ArrayList();
+        List<Coding> bestFits = new ArrayList<>();
+        List<Coding> fullFits = new ArrayList<>();
+        List<Coding> longFits = new ArrayList<>();
         final int PACK_TO_MAX_S = 1;
         if (bestPopFVC <= 255) {
             bestFits.add(BandStructure.BYTE1);
@@ -776,16 +777,16 @@
                 }
             }
             // interleave all B greater than bestB with best and full fits
-            for (Iterator i = bestFits.iterator(); i.hasNext(); ) {
-                Coding c = (Coding) i.next();
+            for (Iterator<Coding> i = bestFits.iterator(); i.hasNext(); ) {
+                Coding c = i.next();
                 if (c.B() > bestB) {
                     i.remove();
                     longFits.add(0, c);
                 }
             }
         }
-        ArrayList allFits = new ArrayList();
-        for (Iterator i = bestFits.iterator(),
+        List<Coding> allFits = new ArrayList<>();
+        for (Iterator<Coding> i = bestFits.iterator(),
                       j = fullFits.iterator(),
                       k = longFits.iterator();
              i.hasNext() || j.hasNext() || k.hasNext(); ) {
@@ -812,8 +813,7 @@
         }
         if (verbose > 3)
             Utils.log.info("allFits: "+allFits);
-        for (Iterator i = allFits.iterator(); i.hasNext(); ) {
-            Coding tc = (Coding) i.next();
+        for (Coding tc : allFits) {
             boolean packToMax = false;
             if (tc.S() == PACK_TO_MAX_S) {
                 // Kludge:  setS(PACK_TO_MAX_S) means packToMax here.
@@ -910,7 +910,7 @@
                              " tc="+pop.tokenCoding+
                              " uc="+pop.unfavoredCoding);
             //pop.hist.print("pop-hist", null, System.out);
-            StringBuffer sb = new StringBuffer();
+            StringBuilder sb = new StringBuilder();
             sb.append("fv = {");
             for (int i = 1; i <= fVlen; i++) {
                 if ((i % 10) == 0)
@@ -949,20 +949,20 @@
         // run occupies too much space.  ("Too much" means, say 5% more
         // than the average integer size of the band as a whole.)
         // Try to find a better coding for those segments.
-        int   start  = this.start;
-        int   end    = this.end;
-        int[] values = this.values;
-        int len = end-start;
+        int   lstart  = this.start;
+        int   lend    = this.end;
+        int[] lvalues = this.values;
+        int len = lend-lstart;
         if (plainCoding.isDelta()) {
-            values = getDeltas(0,0); //%%% not quite right!
-            start = 0;
-            end = values.length;
+            lvalues = getDeltas(0,0); //%%% not quite right!
+            lstart = 0;
+            lend = lvalues.length;
         }
         int[] sizes = new int[len+1];
         int fillp = 0;
         int totalSize = 0;
-        for (int i = start; i < end; i++) {
-            int val = values[i];
+        for (int i = lstart; i < lend; i++) {
+            int val = lvalues[i];
             sizes[fillp++] = totalSize;
             int size = plainCoding.getLength(val);
             assert(size < Integer.MAX_VALUE);
@@ -1013,22 +1013,23 @@
         double[] fuzzes   = new double[meshes.length];
         for (int i = 0; i < meshes.length; i++) {
             int mesh = meshes[i];
-            double fuzz;
+            double lfuzz;
             if (mesh < 10)
-                fuzz = sizeFuzz3;
+                lfuzz = sizeFuzz3;
             else if (mesh < 100)
-                fuzz = sizeFuzz2;
+                lfuzz = sizeFuzz2;
             else
-                fuzz = sizeFuzz;
-            fuzzes[i] = fuzz;
-            threshes[i] = BAND_HEADER + (int)Math.ceil(mesh * avgSize * fuzz);
+                lfuzz = sizeFuzz;
+            fuzzes[i] = lfuzz;
+            threshes[i] = BAND_HEADER + (int)Math.ceil(mesh * avgSize * lfuzz);
         }
         if (verbose > 1) {
             System.out.print("tryAdaptiveCoding ["+len+"]"+
                              " avgS="+avgSize+" fuzz="+sizeFuzz+
                              " meshes: {");
-            for (int i = 0; i < meshes.length; i++)
-                System.out.print(" "+meshes[i]+"("+threshes[i]+")");
+            for (int i = 0; i < meshes.length; i++) {
+                System.out.print(" " + meshes[i] + "(" + threshes[i] + ")");
+            }
             Utils.log.info(" }");
         }
         if (runHelper == null) {
@@ -1229,20 +1230,19 @@
         Histogram hist = getValueHistogram();
         int fVlen = stressLen(hist.getTotalLength());
         if (fVlen == 0)  return coding;
-        List popvals = new ArrayList();
+        List<Integer> popvals = new ArrayList<>();
         if (stress.nextBoolean()) {
             // Build the population from the value list.
-            HashSet popset = new HashSet();
+            Set<Integer> popset = new HashSet<>();
             for (int i = start; i < end; i++) {
-                Integer val = new Integer(values[i]);
-                if (popset.add(val))  popvals.add(val);
+                if (popset.add(values[i]))  popvals.add(values[i]);
             }
         } else {
             int[][] matrix = hist.getMatrix();
             for (int mrow = 0; mrow < matrix.length; mrow++) {
                 int[] row = matrix[mrow];
                 for (int mcol = 1; mcol < row.length; mcol++) {
-                    popvals.add(new Integer(row[mcol]));
+                    popvals.add(row[mcol]);
                 }
             }
         }
@@ -1269,7 +1269,7 @@
         fVlen = popvals.size();
         int[] fvals = new int[1+fVlen];
         for (int i = 0; i < fVlen; i++) {
-            fvals[1+i] = ((Integer)popvals.get(i)).intValue();
+            fvals[1+i] = (popvals.get(i)).intValue();
         }
         PopulationCoding pop = new PopulationCoding();
         pop.setFavoredValues(fvals, fVlen);
@@ -1283,13 +1283,13 @@
             }
         }
         if (pop.tokenCoding == null) {
-            int min = fvals[1], max = min;
+            int lmin = fvals[1], lmax = lmin;
             for (int i = 2; i <= fVlen; i++) {
                 int val = fvals[i];
-                if (min > val)  min = val;
-                if (max < val)  max = val;
+                if (lmin > val)  lmin = val;
+                if (lmax < val)  lmax = val;
             }
-            pop.tokenCoding = stressCoding(min, max);
+            pop.tokenCoding = stressCoding(lmin, lmax);
         }
 
         computePopSizePrivate(pop, valueCoding, valueCoding);
@@ -1310,13 +1310,13 @@
         try {
             assert(!disableRunCoding);
             disableRunCoding = true;  // temporary, while I decide spans
-            int[] allValues = (int[]) values.clone();
+            int[] allValues = values.clone();
             CodingMethod result = null;
             int scan  = this.end;
-            int start = this.start;
-            for (int split; scan > start; scan = split) {
+            int lstart = this.start;
+            for (int split; scan > lstart; scan = split) {
                 int thisspan;
-                int rand = (scan - start < 100)? -1: stress.nextInt();
+                int rand = (scan - lstart < 100)? -1: stress.nextInt();
                 if ((rand & 7) != 0) {
                     thisspan = (spanlen==1? spanlen: stressLen(spanlen-1)+1);
                 } else {
@@ -1325,7 +1325,7 @@
                     int KB = (rand >>>= 3) & AdaptiveCoding.KB_MAX;
                     for (;;) {
                         thisspan = AdaptiveCoding.decodeK(KX, KB);
-                        if (thisspan <= scan - start)  break;
+                        if (thisspan <= scan - lstart)  break;
                         // Try smaller and smaller codings:
                         if (KB != AdaptiveCoding.KB_DEFAULT)
                             KB = AdaptiveCoding.KB_DEFAULT;
@@ -1335,11 +1335,13 @@
                     //System.out.println("KX="+KX+" KB="+KB+" K="+thisspan);
                     assert(AdaptiveCoding.isCodableLength(thisspan));
                 }
-                if (thisspan > scan - start)  thisspan = scan - start;
-                while (!AdaptiveCoding.isCodableLength(thisspan))  --thisspan;
+                if (thisspan > scan - lstart)  thisspan = scan - lstart;
+                while (!AdaptiveCoding.isCodableLength(thisspan)) {
+                    --thisspan;
+                }
                 split = scan - thisspan;
                 assert(split < scan);
-                assert(split >= start);
+                assert(split >= lstart);
                 // Choose a coding for the span [split..scan).
                 CodingMethod sc = choose(allValues, split, scan, plainCoding);
                 if (result == null) {
@@ -1420,7 +1422,7 @@
                 case StreamTokenizer.TT_EOF:
                     throw new NoSuchElementException();
                 case StreamTokenizer.TT_NUMBER:
-                    return new Integer((int) in.nval);
+                    return Integer.valueOf((int) in.nval);
                 default:
                     assert(false);
                     return null;
diff --git a/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java b/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java
index abafbd9..3b851ef 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java
@@ -33,13 +33,14 @@
 import java.util.ListIterator;
 import java.util.Map;
 import java.util.Set;
+import static com.sun.java.util.jar.pack.Constants.*;
 
 /**
  * Representation of constant pool entries and indexes.
  * @author John Rose
  */
 abstract
-class ConstantPool implements Constants {
+class ConstantPool {
     private ConstantPool() {}  // do not instantiate
 
     static int verbose() {
@@ -155,9 +156,6 @@
             return null;
         }
 
-        public boolean sameTagAs(Object o) {
-            return (o instanceof Entry) && ((Entry)o).tag == tag;
-        }
         public boolean eq(Entry that) {  // same reference
             assert(that != null);
             return this == that || this.equals(that);
@@ -219,9 +217,9 @@
             return value.hashCode();
         }
         public boolean equals(Object o) {
-            if (!sameTagAs(o))  return false;
             // Use reference equality of interned strings:
-            return ((Utf8Entry)o).value == value;
+            return (o != null && o.getClass() == Utf8Entry.class
+                    && ((Utf8Entry) o).value.equals(value));
         }
         public int compareTo(Object o) {
             int x = superCompareTo(o);
@@ -275,8 +273,9 @@
         }
 
         public boolean equals(Object o) {
-            if (!sameTagAs(o))  return false;
-            return (((NumberEntry)o).value).equals(value);
+            return (o != null && o.getClass() == NumberEntry.class
+                    && ((NumberEntry) o).value.equals(value));
+
         }
         public int compareTo(Object o) {
             int x = superCompareTo(o);
@@ -310,8 +309,8 @@
             return ref.hashCode() + tag;
         }
         public boolean equals(Object o) {
-            if (!sameTagAs(o))  return false;
-            return ((StringEntry)o).ref.eq(ref);
+            return (o != null && o.getClass() == StringEntry.class &&
+                    ((StringEntry)o).ref.eq(ref));
         }
         public int compareTo(Object o) {
             int x = superCompareTo(o);
@@ -342,8 +341,8 @@
             hashCode();  // force computation of valueHash
         }
         public boolean equals(Object o) {
-            if (!sameTagAs(o))  return false;
-            return ((ClassEntry)o).ref.eq(ref);
+            return (o != null && o.getClass() == ClassEntry.class
+                    && ((ClassEntry) o).ref.eq(ref));
         }
         public int compareTo(Object o) {
             int x = superCompareTo(o);
@@ -380,7 +379,9 @@
             return (nameRef.hashCode() + (hc2 << 8)) ^ hc2;
         }
         public boolean equals(Object o) {
-            if (!sameTagAs(o))  return false;
+            if (o == null || o.getClass() != DescriptorEntry.class) {
+                return false;
+            }
             DescriptorEntry that = (DescriptorEntry)o;
             return this.nameRef.eq(that.nameRef)
                 && this.typeRef.eq(that.typeRef);
@@ -439,7 +440,9 @@
             hashCode();  // force computation of valueHash
         }
         public boolean equals(Object o) {
-            if (!sameTagAs(o))  return false;
+            if (o == null || o.getClass() != MemberEntry.class) {
+                return false;
+            }
             MemberEntry that = (MemberEntry)o;
             return this.classRef.eq(that.classRef)
                 && this.descRef.eq(that.descRef);
@@ -511,8 +514,8 @@
         }
 
         public boolean equals(Object o) {
-            if (!sameTagAs(o))  return false;
-            return ((SignatureEntry)o).value == value;
+            return (o != null && o.getClass() == SignatureEntry.class &&
+                    ((SignatureEntry)o).value.equals(value));
         }
         public int compareTo(Object o) {
             int x = superCompareTo(o);
@@ -724,7 +727,7 @@
     protected static final ClassEntry[] noClassRefs = {};
 
     /** An Index is a mapping between CP entries and small integers. */
-    public static
+    public static final
     class Index extends AbstractList {
         protected String debugName;
         protected Entry[] cpMap;
@@ -894,7 +897,7 @@
     }
 
     public static
-    Index makeIndex(String debugName, Collection cpMapList) {
+    Index makeIndex(String debugName, Collection<Entry> cpMapList) {
         return new Index(debugName, cpMapList);
     }
 
@@ -916,7 +919,7 @@
     public static
     Index[] partition(Index ix, int[] keys) {
         // %%% Should move this into class Index.
-        ArrayList<List<Entry>> parts = new ArrayList<>();
+        List<List<Entry>> parts = new ArrayList<>();
         Entry[] cpMap = ix.cpMap;
         assert(keys.length == cpMap.length);
         for (int i = 0; i < keys.length; i++) {
@@ -1094,12 +1097,12 @@
 
         // Inverse of getOverloadingIndex
         public MemberEntry getOverloadingForIndex(byte tag, ClassEntry classRef, String name, int which) {
-            assert(name == name.intern());
+            assert(name.equals(name.intern()));
             Index ix = getMemberIndex(tag, classRef);
             int ord = 0;
             for (int i = 0; i < ix.cpMap.length; i++) {
                 MemberEntry e = (MemberEntry) ix.cpMap[i];
-                if (e.descRef.nameRef.stringValue() == name) {
+                if (e.descRef.nameRef.stringValue().equals(name)) {
                     if (ord == which)  return e;
                     ord++;
                 }
@@ -1133,10 +1136,10 @@
     public static
     void completeReferencesIn(Set<Entry> cpRefs, boolean flattenSigs) {
         cpRefs.remove(null);
-        for (ListIterator work =
-                 new ArrayList(cpRefs).listIterator(cpRefs.size());
+        for (ListIterator<Entry> work =
+                 new ArrayList<>(cpRefs).listIterator(cpRefs.size());
              work.hasPrevious(); ) {
-            Entry e = (Entry) work.previous();
+            Entry e = work.previous();
             work.remove();          // pop stack
             assert(e != null);
             if (flattenSigs && e.tag == CONSTANT_Signature) {
diff --git a/src/share/classes/com/sun/java/util/jar/pack/Constants.java b/src/share/classes/com/sun/java/util/jar/pack/Constants.java
index 512dac7..2e4cb37 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/Constants.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/Constants.java
@@ -32,7 +32,10 @@
  * Shared constants
  * @author John Rose
  */
-interface Constants {
+class Constants {
+
+    private Constants(){}
+
     public final static int JAVA_MAGIC = 0xCAFEBABE;
 
     /*
diff --git a/src/share/classes/com/sun/java/util/jar/pack/Driver.java b/src/share/classes/com/sun/java/util/jar/pack/Driver.java
index a7c47a8..36885a8 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/Driver.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/Driver.java
@@ -59,12 +59,11 @@
                 ResourceBundle.getBundle("com.sun.java.util.jar.pack.DriverResource");
 
     public static void main(String[] ava) throws IOException {
-        ArrayList<String> av = new ArrayList<>(Arrays.asList(ava));
+        List<String> av = new ArrayList<>(Arrays.asList(ava));
 
         boolean doPack   = true;
         boolean doUnpack = false;
         boolean doRepack = false;
-        boolean doForceRepack = false;
         boolean doZip = true;
         String logFile = null;
         String verboseProp = Utils.DEBUG_VERBOSE;
@@ -72,17 +71,20 @@
         {
             // Non-standard, undocumented "--unpack" switch enables unpack mode.
             String arg0 = av.isEmpty() ? "" : av.get(0);
-            if (arg0.equals("--pack")) {
+            switch (arg0) {
+                case "--pack":
                 av.remove(0);
-            } else if (arg0.equals("--unpack")) {
+                    break;
+                case "--unpack":
                 av.remove(0);
                 doPack = false;
                 doUnpack = true;
+                    break;
             }
         }
 
         // Collect engine properties here:
-        HashMap<String,String> engProps = new HashMap<>();
+        Map<String,String> engProps = new HashMap<>();
         engProps.put(verboseProp, System.getProperty(verboseProp));
 
         String optionMap;
@@ -96,7 +98,7 @@
         }
 
         // Collect argument properties here:
-        HashMap<String,String> avProps = new HashMap<>();
+        Map<String,String> avProps = new HashMap<>();
         try {
             for (;;) {
                 String state = parseCommandOptions(av, optionMap, avProps);
@@ -146,7 +148,7 @@
                 }
 
                 // See if there is any other action to take.
-                if (state == "--config-file=") {
+                if ("--config-file=".equals(state)) {
                     String propFile = av.remove(0);
                     InputStream propIn = new FileInputStream(propFile);
                     Properties fileProps = new Properties();
@@ -157,10 +159,10 @@
                     for (Map.Entry<Object,Object> me : fileProps.entrySet()) {
                         engProps.put((String) me.getKey(), (String) me.getValue());
                     }
-                } else if (state == "--version") {
+                } else if ("--version".equals(state)) {
                         System.out.println(MessageFormat.format(RESOURCE.getString(DriverResource.VERSION), Driver.class.getName(), "1.31, 07/05/05"));
                     return;
-                } else if (state == "--help") {
+                } else if ("--help".equals(state)) {
                     printUsage(doPack, true, System.out);
                     System.exit(1);
                     return;
@@ -178,14 +180,20 @@
         // Deal with remaining non-engine properties:
         for (String opt : avProps.keySet()) {
             String val = avProps.get(opt);
-            if (opt == "--repack") {
-                doRepack = true;
-            } else if (opt == "--no-gzip") {
-                doZip = (val == null);
-            } else if (opt == "--log-file=") {
-                logFile = val;
-            } else {
-            throw new InternalError(MessageFormat.format(RESOURCE.getString(DriverResource.BAD_OPTION), opt, avProps.get(opt)));
+            switch (opt) {
+                case "--repack":
+                    doRepack = true;
+                    break;
+                case "--no-gzip":
+                    doZip = (val == null);
+                    break;
+                case "--log-file=":
+                    logFile = val;
+                    break;
+                default:
+                    throw new InternalError(MessageFormat.format(
+                            RESOURCE.getString(DriverResource.BAD_OPTION),
+                            opt, avProps.get(opt)));
             }
         }
 
@@ -219,7 +227,9 @@
             if (packfile.toLowerCase().endsWith(".pack") ||
                 packfile.toLowerCase().endsWith(".pac") ||
                 packfile.toLowerCase().endsWith(".gz")) {
-            System.err.println(MessageFormat.format(RESOURCE.getString(DriverResource.BAD_REPACK_OUTPUT),packfile));
+                System.err.println(MessageFormat.format(
+                        RESOURCE.getString(DriverResource.BAD_REPACK_OUTPUT),
+                        packfile));
                 printUsage(doPack, false, System.err);
                 System.exit(2);
             }
diff --git a/src/share/classes/com/sun/java/util/jar/pack/FixedList.java b/src/share/classes/com/sun/java/util/jar/pack/FixedList.java
new file mode 100644
index 0000000..450635a
--- /dev/null
+++ b/src/share/classes/com/sun/java/util/jar/pack/FixedList.java
@@ -0,0 +1,174 @@
+/*
+ * 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.java.util.jar.pack;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+
+/*
+ * @author ksrini
+ */
+
+/*
+ * This class provides an ArrayList implementation which has a fixed size,
+ * thus all the operations which modifies the size have been rendered
+ * inoperative. This essentially allows us to use generified array
+ * lists in lieu of arrays.
+ */
+final class FixedList<E> implements List<E> {
+
+    private final ArrayList<E> flist;
+
+    protected FixedList(int capacity) {
+        flist = new ArrayList<>(capacity);
+        // initialize the list to null
+        for (int i = 0 ; i < capacity ; i++) {
+            flist.add(null);
+        }
+    }
+    @Override
+    public int size() {
+        return flist.size();
+    }
+
+    @Override
+    public boolean isEmpty() {
+        return flist.isEmpty();
+    }
+
+    @Override
+    public boolean contains(Object o) {
+        return flist.contains(o);
+    }
+
+    @Override
+    public Iterator<E> iterator() {
+        return flist.iterator();
+    }
+
+    @Override
+    public Object[] toArray() {
+        return flist.toArray();
+    }
+
+    @Override
+    public <T> T[] toArray(T[] a) {
+        return flist.toArray(a);
+    }
+
+    @Override
+    public boolean add(E e) throws UnsupportedOperationException {
+        throw new UnsupportedOperationException("operation not permitted");
+    }
+
+    @Override
+    public boolean remove(Object o) throws UnsupportedOperationException {
+        throw new UnsupportedOperationException("operation not permitted");
+    }
+
+    @Override
+    public boolean containsAll(Collection<?> c) {
+        return flist.containsAll(c);
+    }
+
+    @Override
+    public boolean addAll(Collection<? extends E> c) throws UnsupportedOperationException {
+        throw new UnsupportedOperationException("operation not permitted");
+    }
+
+    @Override
+    public boolean addAll(int index, Collection<? extends E> c) throws UnsupportedOperationException {
+         throw new UnsupportedOperationException("operation not permitted");
+    }
+
+    @Override
+    public boolean removeAll(Collection<?> c)  throws UnsupportedOperationException  {
+         throw new UnsupportedOperationException("operation not permitted");
+    }
+
+    @Override
+    public boolean retainAll(Collection<?> c)  throws UnsupportedOperationException  {
+        throw new UnsupportedOperationException("operation not permitted");
+    }
+
+    @Override
+    public void clear()  throws UnsupportedOperationException {
+        throw new UnsupportedOperationException("operation not permitted");
+    }
+
+    @Override
+    public E get(int index) {
+        return flist.get(index);
+    }
+
+    @Override
+    public E set(int index, E element) {
+        return flist.set(index, element);
+    }
+
+    @Override
+    public void add(int index, E element)  throws UnsupportedOperationException {
+        throw new UnsupportedOperationException("operation not permitted");
+    }
+
+    @Override
+    public E remove(int index)   throws UnsupportedOperationException {
+        throw new UnsupportedOperationException("operation not permitted");
+    }
+
+    @Override
+    public int indexOf(Object o) {
+        return flist.indexOf(o);
+    }
+
+    @Override
+    public int lastIndexOf(Object o) {
+        return flist.lastIndexOf(o);
+    }
+
+    @Override
+    public ListIterator<E> listIterator() {
+        return flist.listIterator();
+    }
+
+    @Override
+    public ListIterator<E> listIterator(int index) {
+        return flist.listIterator(index);
+    }
+
+    @Override
+    public List<E> subList(int fromIndex, int toIndex) {
+        return flist.subList(fromIndex, toIndex);
+    }
+
+    @Override
+    public String toString() {
+        return "FixedList{" + "plist=" + flist + '}';
+    }
+}
+
diff --git a/src/share/classes/com/sun/java/util/jar/pack/Fixups.java b/src/share/classes/com/sun/java/util/jar/pack/Fixups.java
index bb346be..15c5208 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/Fixups.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/Fixups.java
@@ -42,7 +42,7 @@
  *
  * @author John Rose
  */
-class Fixups extends AbstractCollection implements Constants {
+final class Fixups extends AbstractCollection {
     byte[] bytes;    // the subject of the relocations
     int head;        // desc locating first reloc
     int tail;        // desc locating last reloc
@@ -99,7 +99,7 @@
         }
     }
 
-    public void visitRefs(Collection refs) {
+    public void visitRefs(Collection<Entry> refs) {
         for (int i = 0; i < size; i++) {
             refs.add(entries[i]);
         }
@@ -124,6 +124,7 @@
         return bytes;
     }
 
+    @SuppressWarnings("unchecked")
     public void setBytes(byte[] newBytes) {
         if (bytes == newBytes)  return;
         ArrayList old = null;
@@ -278,7 +279,7 @@
             return new Fixup(nextDesc(), entries[thisIndex]);
         }
         int nextDesc() {
-            int thisIndex = index++;
+            index++;
             int thisDesc = next;
             if (index < size) {
                 // Fetch next desc eagerly, in case this fixup gets finalized.
@@ -310,6 +311,7 @@
     public boolean add(Object fixup) {
         return add((Fixup) fixup);
     }
+    @SuppressWarnings("unchecked")
     public boolean addAll(Collection c) {
         if (c instanceof Fixups) {
             // Use knowledge of Itr structure to avoid building little structs.
@@ -420,7 +422,7 @@
 
     // Iterate over all the references in this set of fixups.
     public static
-    void visitRefs(Object fixups, Collection refs) {
+    void visitRefs(Object fixups, Collection<Entry> refs) {
         if (fixups == null) {
         } else if (!(fixups instanceof Fixups)) {
             // Special convention; see above.
diff --git a/src/share/classes/com/sun/java/util/jar/pack/Histogram.java b/src/share/classes/com/sun/java/util/jar/pack/Histogram.java
index b5c7655..2616405 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/Histogram.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/Histogram.java
@@ -34,7 +34,7 @@
  * Histogram derived from an integer array of events (int[]).
  * @author John Rose
  */
-class Histogram {
+final class Histogram {
     // Compact histogram representation:  4 bytes per distinct value,
     // plus 5 words per distinct count.
     protected final int[][] matrix;  // multi-row matrix {{counti,valueij...}}
@@ -304,7 +304,7 @@
     public
     String[] getRowTitles(String name) {
         int totalUnique = getTotalLength();
-        int totalWeight = getTotalWeight();
+        int ltotalWeight = getTotalWeight();
         String[] histTitles = new String[matrix.length];
         int cumWeight = 0;
         int cumUnique = 0;
@@ -314,7 +314,7 @@
             int weight = getRowWeight(i);
             cumWeight += weight;
             cumUnique += unique;
-            long wpct = ((long)cumWeight * 100 + totalWeight/2) / totalWeight;
+            long wpct = ((long)cumWeight * 100 + ltotalWeight/2) / ltotalWeight;
             long upct = ((long)cumUnique * 100 + totalUnique/2) / totalUnique;
             double len = getRowBitLength(i);
             assert(0.1 > Math.abs(len - getBitLength(matrix[i][1])));
@@ -346,14 +346,14 @@
     public
     void print(String name, String[] histTitles, PrintStream out) {
         int totalUnique = getTotalLength();
-        int totalWeight = getTotalWeight();
+        int ltotalWeight = getTotalWeight();
         double tlen = getBitLength();
-        double avgLen = tlen / totalWeight;
-        double avg = (double) totalWeight / totalUnique;
+        double avgLen = tlen / ltotalWeight;
+        double avg = (double) ltotalWeight / totalUnique;
         String title = (name
                         +" len="+round(tlen,10)
                         +" avgLen="+round(avgLen,10)
-                        +" weight("+totalWeight+")"
+                        +" weight("+ltotalWeight+")"
                         +" unique["+totalUnique+"]"
                         +" avgWeight("+round(avg,100)+")");
         if (histTitles == null) {
@@ -363,9 +363,9 @@
             StringBuffer buf = new StringBuffer();
             for (int i = 0; i < matrix.length; i++) {
                 buf.setLength(0);
-                buf.append("  "+histTitles[i]+" {");
+                buf.append("  ").append(histTitles[i]).append(" {");
                 for (int j = 1; j < matrix[i].length; j++) {
-                    buf.append(" "+matrix[i][j]);
+                    buf.append(" ").append(matrix[i][j]);
                 }
                 buf.append(" }");
                 out.println(buf);
@@ -603,7 +603,7 @@
     private static
     int[] maybeSort(int[] values) {
         if (!isSorted(values, 0, false)) {
-            values = (int[]) values.clone();
+            values = values.clone();
             Arrays.sort(values);
         }
         return values;
diff --git a/src/share/classes/com/sun/java/util/jar/pack/Instruction.java b/src/share/classes/com/sun/java/util/jar/pack/Instruction.java
index b05d6ff..e0744e2 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/Instruction.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/Instruction.java
@@ -26,13 +26,15 @@
 package com.sun.java.util.jar.pack;
 
 import java.io.IOException;
+import java.util.Arrays;
+import static com.sun.java.util.jar.pack.Constants.*;
 
 /**
  * A parsed bytecode instruction.
  * Provides accessors to various relevant bits.
  * @author John Rose
  */
-class Instruction implements Constants {
+class Instruction  {
     protected byte[] bytes;  // bytecodes
     protected int pc;        // location of this instruction
     protected int bc;        // opcode of this instruction
@@ -91,8 +93,8 @@
 
     /** A fake instruction at this pc whose next() will be at nextpc. */
     public Instruction forceNextPC(int nextpc) {
-        int length = nextpc - pc;
-        return new Instruction(bytes, pc, -1, -1, length);
+        int llength = nextpc - pc;
+        return new Instruction(bytes, pc, -1, -1, llength);
     }
 
     public static Instruction at(byte[] bytes, int pc) {
@@ -315,12 +317,24 @@
         }
     }
 
-    /** Two insns are equal if they have the same bytes. */
+    /** Two instructions are equal if they have the same bytes. */
     public boolean equals(Object o) {
-        return (o instanceof Instruction) && equals((Instruction)o);
+        return (o != null) && (o.getClass() == Instruction.class)
+                && equals((Instruction) o);
+    }
+
+    public int hashCode() {
+        int hash = 3;
+        hash = 11 * hash + Arrays.hashCode(this.bytes);
+        hash = 11 * hash + this.pc;
+        hash = 11 * hash + this.bc;
+        hash = 11 * hash + this.w;
+        hash = 11 * hash + this.length;
+        return hash;
     }
 
     public boolean equals(Instruction that) {
+        if (this.pc != that.pc)            return false;
         if (this.bc != that.bc)            return false;
         if (this.w  != that.w)             return false;
         if (this.length  != that.length)   return false;
diff --git a/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java b/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java
index 2ea9f4d..baa70b6 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java
@@ -170,8 +170,8 @@
 
     void run(InputStream inRaw, JarOutputStream jstream,
              ByteBuffer presetInput) throws IOException {
-        BufferedInputStream in = new BufferedInputStream(inRaw);
-        this.in = in;    // for readInputFn to see
+        BufferedInputStream in0 = new BufferedInputStream(inRaw);
+        this.in = in0;    // for readInputFn to see
         _verbose = _props.getInteger(Utils.DEBUG_VERBOSE);
         // Fix for BugId: 4902477, -unpack.modification.time = 1059010598000
         // TODO eliminate and fix in unpack.cpp
@@ -224,7 +224,7 @@
             if (_verbose > 0)
                 Utils.log.info("bytes consumed = "+consumed);
             if (presetInput == null &&
-                !Utils.isPackMagic(Utils.readMagic(in))) {
+                !Utils.isPackMagic(Utils.readMagic(in0))) {
                 break;
             }
             if (_verbose > 0 ) {
diff --git a/src/share/classes/com/sun/java/util/jar/pack/Package.java b/src/share/classes/com/sun/java/util/jar/pack/Package.java
index 981bd53..2a75f74 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/Package.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/Package.java
@@ -52,12 +52,13 @@
 import java.util.Map;
 import java.util.Set;
 import java.util.jar.JarFile;
+import static com.sun.java.util.jar.pack.Constants.*;
 
 /**
  * Define the main data structure transmitted by pack/unpack.
  * @author John Rose
  */
-class Package implements Constants {
+class Package {
     int verbose;
     {
         PropMap pmap = Utils.currentPropMap();
@@ -109,9 +110,9 @@
     public static final Attribute.Layout attrCodeEmpty;
     public static final Attribute.Layout attrInnerClassesEmpty;
     public static final Attribute.Layout attrSourceFileSpecial;
-    public static final Map attrDefs;
+    public static final Map<Attribute.Layout, Attribute> attrDefs;
     static {
-        HashMap<Layout, Attribute> ad = new HashMap<>(3);
+        Map<Layout, Attribute> ad = new HashMap<>(3);
         attrCodeEmpty = Attribute.define(ad, ATTR_CONTEXT_METHOD,
                                          "Code", "").layout();
         attrInnerClassesEmpty = Attribute.define(ad, ATTR_CONTEXT_CLASS,
@@ -130,8 +131,7 @@
      */
     int getHighestClassVersion() {
         int res = 0;  // initial low value
-        for (Iterator i = classes.iterator(); i.hasNext(); ) {
-            Class cls = (Class) i.next();
+        for (Class cls : classes) {
             int ver = cls.getVersion();
             if (res < ver)  res = ver;
         }
@@ -187,7 +187,7 @@
         return classes;
     }
 
-    public
+    public final
     class Class extends Attribute.Holder implements Comparable {
         public Package getPackage() { return Package.this; }
 
@@ -232,8 +232,8 @@
             initFile(newStub(classFile));
         }
 
-        List getFields() { return fields == null ? noFields : fields; }
-        List getMethods() { return methods == null ? noMethods : methods; }
+        List<Field> getFields() { return fields == null ? noFields : fields; }
+        List<Method> getMethods() { return methods == null ? noMethods : methods; }
 
         public String getName() {
             return thisClass.stringValue();
@@ -264,7 +264,7 @@
             if (olda == null)
                 return;  // no SourceFile attr.
             String obvious = getObviousSourceFile();
-            ArrayList ref = new ArrayList(1);
+            List<Entry> ref = new ArrayList<>(1);
             olda.visitRefs(this, VRM_PACKAGE, ref);
             Utf8Entry sfName = (Utf8Entry) ref.get(0);
             Attribute a = olda;
@@ -322,7 +322,7 @@
         }
 
         public void setInnerClasses(Collection<InnerClass> ics) {
-            innerClasses = (ics == null) ? null : new ArrayList<InnerClass>(ics);
+            innerClasses = (ics == null) ? null : new ArrayList<>(ics);
             // Edit the attribute list, if necessary.
             Attribute a = getAttribute(attrInnerClassesEmpty);
             if (innerClasses != null && a == null)
@@ -341,7 +341,7 @@
          *  with that of Package.this.allInnerClasses.
          */
         public List<InnerClass> computeGloballyImpliedICs() {
-            HashSet<Entry> cpRefs = new HashSet<>();
+            Set<Entry> cpRefs = new HashSet<>();
             {   // This block temporarily displaces this.innerClasses.
                 ArrayList<InnerClass> innerClassesSaved = innerClasses;
                 innerClasses = null;  // ignore for the moment
@@ -350,7 +350,7 @@
             }
             ConstantPool.completeReferencesIn(cpRefs, true);
 
-            HashSet<Entry> icRefs = new HashSet<>();
+            Set<Entry> icRefs = new HashSet<>();
             for (Entry e : cpRefs) {
                 // Restrict cpRefs to InnerClasses entries only.
                 if (!(e instanceof ClassEntry))  continue;
@@ -390,7 +390,7 @@
             List<InnerClass> impliedICs = computeGloballyImpliedICs();
             List<InnerClass> actualICs  = getInnerClasses();
             if (actualICs == null)
-                actualICs = Collections.EMPTY_LIST;
+                actualICs = Collections.emptyList();
 
             // Symmetric difference is calculated from I, A like this:
             //  diff = (I+A) - (I*A)
@@ -409,7 +409,7 @@
                 // Diff is A since I is empty.
             }
             // (I*A) is non-trivial
-            HashSet<InnerClass> center = new HashSet<>(actualICs);
+            Set<InnerClass> center = new HashSet<>(actualICs);
             center.retainAll(new HashSet<>(impliedICs));
             impliedICs.addAll(actualICs);
             impliedICs.removeAll(center);
@@ -443,7 +443,7 @@
             } else if (actualICs == null) {
                 // No local IC attribute, even though some are implied.
                 // Signal with trivial attribute.
-                localICs = Collections.EMPTY_LIST;
+                localICs = Collections.emptyList();
             } else {
                 // Transmit a non-empty diff, which will create
                 // a local ICs attribute.
@@ -588,7 +588,7 @@
             }
 
             public void strip(String attrName) {
-                if (attrName == "Code")
+                if ("Code".equals(attrName))
                     code = null;
                 if (code != null)
                     code.strip(attrName);
@@ -622,7 +622,7 @@
         }
 
         public void strip(String attrName) {
-            if (attrName == "InnerClass")
+            if ("InnerClass".equals(attrName))
                 innerClasses = null;
             for (int isM = 0; isM <= 1; isM++) {
                 ArrayList members = (isM == 0) ? fields : methods;
@@ -639,9 +639,7 @@
             if (verbose > 2)  Utils.log.fine("visitRefs "+this);
             refs.add(thisClass);
             refs.add(superClass);
-            for (int i = 0; i < interfaces.length; i++) {
-                refs.add(interfaces[i]);
-            }
+            refs.addAll(Arrays.asList(interfaces));
             for (int isM = 0; isM <= 1; isM++) {
                 ArrayList members = (isM == 0) ? fields : methods;
                 if (members == null)  continue;
@@ -741,7 +739,7 @@
     }
 
     public List<File> getClassStubs() {
-        ArrayList<File> classStubs = new ArrayList<>(classes.size());
+        List<File> classStubs = new ArrayList<>(classes.size());
         for (Class cls : classes) {
             assert(cls.file.isClassStub());
             classStubs.add(cls.file);
@@ -749,8 +747,7 @@
         return classStubs;
     }
 
-    public
-    class File implements Comparable {
+    public final class File implements Comparable {
         String nameString;  // true name of this file
         Utf8Entry name;
         int modtime = NO_MODTIME;
@@ -792,8 +789,10 @@
         // The nameString is the key.  Ignore other things.
         // (Note:  The name might be "", in the case of a trivial class stub.)
         public boolean equals(Object o) {
+            if (o == null || (o.getClass() != File.class))
+                return false;
             File that = (File)o;
-            return that.nameString == this.nameString;
+            return that.nameString.equals(this.nameString);
         }
         public int hashCode() {
             return nameString.hashCode();
@@ -816,9 +815,9 @@
             return getFileName(null);
         }
         public java.io.File getFileName(java.io.File parent) {
-            String name = this.nameString;
+            String lname = this.nameString;
             //if (name.startsWith("./"))  name = name.substring(2);
-            String fname = name.replace('/', java.io.File.separatorChar);
+            String fname = lname.replace('/', java.io.File.separatorChar);
             return new java.io.File(parent, fname);
         }
 
@@ -834,7 +833,7 @@
         }
         public long getFileLength() {
             long len = 0;
-            if (prepend == null && append == null)  return 0;
+            if (prepend == null || append == null)  return 0;
             for (Iterator i = prepend.iterator(); i.hasNext(); ) {
                 byte[] block = (byte[]) i.next();
                 len += block.length;
@@ -843,7 +842,7 @@
             return len;
         }
         public void writeTo(OutputStream out) throws IOException {
-            if (prepend == null && append == null)  return;
+            if (prepend == null || append == null)  return;
             for (Iterator i = prepend.iterator(); i.hasNext(); ) {
                 byte[] block = (byte[]) i.next();
                 out.write(block);
@@ -859,8 +858,8 @@
         }
         public InputStream getInputStream() {
             InputStream in = new ByteArrayInputStream(append.toByteArray());
-            if (prepend.size() == 0)  return in;
-            ArrayList<InputStream> isa = new ArrayList<>(prepend.size()+1);
+            if (prepend.isEmpty())  return in;
+            List<InputStream> isa = new ArrayList<>(prepend.size()+1);
             for (Iterator i = prepend.iterator(); i.hasNext(); ) {
                 byte[] bytes = (byte[]) i.next();
                 isa.add(new ByteArrayInputStream(bytes));
@@ -897,11 +896,11 @@
     }
 
     // Is there a globally declared table of inner classes?
-    ArrayList<InnerClass> allInnerClasses = new ArrayList<>();
-    HashMap<ClassEntry, InnerClass>   allInnerClassesByThis;
+    List<InnerClass> allInnerClasses = new ArrayList<>();
+    Map<ClassEntry, InnerClass>   allInnerClassesByThis;
 
     public
-    List getAllInnerClasses() {
+    List<InnerClass> getAllInnerClasses() {
         return allInnerClasses;
     }
 
@@ -955,16 +954,17 @@
             if (parse == null)  return false;
             String pkgOuter = parse[0];
             //String number = parse[1];
-            String name     = parse[2];
+            String lname     = parse[2];
             String haveName  = (this.name == null)  ? null : this.name.stringValue();
             String haveOuter = (outerClass == null) ? null : outerClass.stringValue();
-            boolean predictable = (name == haveName && pkgOuter == haveOuter);
+            boolean lpredictable = (lname == haveName && pkgOuter == haveOuter);
             //System.out.println("computePredictable => "+predictable);
-            return predictable;
+            return lpredictable;
         }
 
         public boolean equals(Object o) {
-            if (o == null)  return false;
+            if (o == null || o.getClass() != InnerClass.class)
+                return false;
             InnerClass that = (InnerClass)o;
             return eq(this.thisClass, that.thisClass)
                 && eq(this.outerClass, that.outerClass)
@@ -999,7 +999,7 @@
 
     // Helper for building InnerClasses attributes.
     static private
-    void visitInnerClassRefs(Collection innerClasses, int mode, Collection<Entry> refs) {
+    void visitInnerClassRefs(Collection<InnerClass> innerClasses, int mode, Collection<Entry> refs) {
         if (innerClasses == null) {
             return;  // no attribute; nothing to do
         }
@@ -1008,8 +1008,7 @@
         }
         if (innerClasses.size() > 0) {
             // Count the entries themselves:
-            for (Iterator i = innerClasses.iterator(); i.hasNext(); ) {
-                InnerClass c = (InnerClass) i.next();
+            for (InnerClass c : innerClasses) {
                 c.visitRefs(mode, refs);
             }
         }
@@ -1117,43 +1116,43 @@
         // what is one of { Debug, Compile, Constant, Exceptions, InnerClasses }
         if (verbose > 0)
             Utils.log.info("Stripping "+what.toLowerCase()+" data and attributes...");
-        if (what == "Debug") {
-            strip("SourceFile");
-            strip("LineNumberTable");
-            strip("LocalVariableTable");
-            strip("LocalVariableTypeTable");
-        }
-        if (what == "Compile") {
-            // Keep the inner classes normally.
-            // Although they have no effect on execution,
-            // the Reflection API exposes them, and JCK checks them.
-            // NO: // strip("InnerClasses");
-            strip("Deprecated");
-            strip("Synthetic");
-        }
-        if (what == "Exceptions") {
-            // Keep the exceptions normally.
-            // Although they have no effect on execution,
-            // the Reflection API exposes them, and JCK checks them.
-            strip("Exceptions");
-        }
-        if (what == "Constant") {
-            stripConstantFields();
+        switch (what) {
+            case "Debug":
+                strip("SourceFile");
+                strip("LineNumberTable");
+                strip("LocalVariableTable");
+                strip("LocalVariableTypeTable");
+                break;
+            case "Compile":
+                // Keep the inner classes normally.
+                // Although they have no effect on execution,
+                // the Reflection API exposes them, and JCK checks them.
+                // NO: // strip("InnerClasses");
+                strip("Deprecated");
+                strip("Synthetic");
+                break;
+            case "Exceptions":
+                // Keep the exceptions normally.
+                // Although they have no effect on execution,
+                // the Reflection API exposes them, and JCK checks them.
+                strip("Exceptions");
+                break;
+            case "Constant":
+                stripConstantFields();
+                break;
         }
     }
 
     public void trimToSize() {
         classes.trimToSize();
-        for (Iterator i = classes.iterator(); i.hasNext(); ) {
-            Class c = (Class)i.next();
+        for (Class c : classes) {
             c.trimToSize();
         }
         files.trimToSize();
     }
 
     public void strip(String attrName) {
-        for (Iterator i = classes.iterator(); i.hasNext(); ) {
-            Class c = (Class)i.next();
+        for (Class c : classes) {
             c.strip(attrName);
         }
     }
@@ -1166,10 +1165,9 @@
     }
 
     public void stripConstantFields() {
-        for (Iterator i = classes.iterator(); i.hasNext(); ) {
-            Class c = (Class) i.next();
-            for (Iterator j = c.fields.iterator(); j.hasNext(); ) {
-                Class.Field f = (Class.Field) j.next();
+        for (Class c : classes) {
+            for (Iterator<Class.Field> j = c.fields.iterator(); j.hasNext(); ) {
+                Class.Field f = j.next();
                 if (Modifier.isFinal(f.flags)
                     // do not strip non-static finals:
                     && Modifier.isStatic(f.flags)
@@ -1189,8 +1187,7 @@
             c.visitRefs(mode, refs);
         }
         if (mode != VRM_CLASSIC) {
-            for (Iterator i = files.iterator(); i.hasNext(); ) {
-                File f = (File)i.next();
+            for (File f : files) {
                 f.visitRefs(mode, refs);
             }
             visitInnerClassRefs(allInnerClasses, mode, refs);
@@ -1202,6 +1199,7 @@
     // compress better.  It also moves classes to the end of the
     // file order.  It also removes JAR directory entries, which
     // are useless.
+    @SuppressWarnings("unchecked")
     void reorderFiles(boolean keepClassOrder, boolean stripDirectories) {
         // First reorder the classes, if that is allowed.
         if (!keepClassOrder) {
@@ -1214,9 +1212,9 @@
         // modtimes and options are not transmitted, and the stub files
         // for class files do not need to be transmitted at all.
         // Also
-        List stubs = getClassStubs();
-        for (Iterator i = files.iterator(); i.hasNext(); ) {
-            File file = (File) i.next();
+        List<File> stubs = getClassStubs();
+        for (Iterator<File> i = files.iterator(); i.hasNext(); ) {
+            File file = i.next();
             if (file.isClassStub() ||
                 (stripDirectories && file.isDirectory())) {
                 i.remove();
@@ -1259,8 +1257,8 @@
 
     void trimStubs() {
         // Restore enough non-trivial stubs to carry the needed class modtimes.
-        for (ListIterator i = files.listIterator(files.size()); i.hasPrevious(); ) {
-            File file = (File) i.previous();
+        for (ListIterator<File> i = files.listIterator(files.size()); i.hasPrevious(); ) {
+            File file = i.previous();
             if (!file.isTrivialClassStub()) {
                 if (verbose > 1)
                     Utils.log.fine("Keeping last non-trivial "+file);
@@ -1309,7 +1307,7 @@
 
     // Use this before writing the class files.
     void ensureAllClassFiles() {
-        HashSet<File> fileSet = new HashSet<>(files);
+        Set<File> fileSet = new HashSet<>(files);
         for (Class cls : classes) {
             // Add to the end of ths list:
             if (!fileSet.contains(cls.file))
@@ -1317,8 +1315,8 @@
         }
     }
 
-    static final List noObjects = Arrays.asList(new Object[0]);
-    static final List noFields = Arrays.asList(new Class.Field[0]);
-    static final List noMethods = Arrays.asList(new Class.Method[0]);
-    static final List noInnerClasses = Arrays.asList(new InnerClass[0]);
+    static final List<Object> noObjects = Arrays.asList(new Object[0]);
+    static final List<Class.Field> noFields = Arrays.asList(new Class.Field[0]);
+    static final List<Class.Method> noMethods = Arrays.asList(new Class.Method[0]);
+    static final List<InnerClass> noInnerClasses = Arrays.asList(new InnerClass[0]);
 }
diff --git a/src/share/classes/com/sun/java/util/jar/pack/PackageReader.java b/src/share/classes/com/sun/java/util/jar/pack/PackageReader.java
index e5aa240..41436e7 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/PackageReader.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/PackageReader.java
@@ -32,11 +32,28 @@
 import com.sun.java.util.jar.pack.ConstantPool.MemberEntry;
 import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry;
 import com.sun.java.util.jar.pack.ConstantPool.Utf8Entry;
-import java.io.*;
-import java.util.*;
 import com.sun.java.util.jar.pack.Package.Class;
 import com.sun.java.util.jar.pack.Package.File;
 import com.sun.java.util.jar.pack.Package.InnerClass;
+import java.io.ByteArrayOutputStream;
+import java.io.EOFException;
+import java.io.PrintStream;
+import java.io.FilterInputStream;
+import java.io.BufferedInputStream;
+import java.io.InputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Set;
+import static com.sun.java.util.jar.pack.Constants.*;
 
 /**
  * Reader for a package file.
@@ -418,7 +435,7 @@
                 cp_Int.readFrom(in);
                 for (int i = 0; i < cpMap.length; i++) {
                     int x = cp_Int.getInt();  // coding handles signs OK
-                    cpMap[i] = ConstantPool.getLiteralEntry(new Integer(x));
+                    cpMap[i] = ConstantPool.getLiteralEntry(x);
                 }
                 cp_Int.doneDisbursing();
                 break;
@@ -428,7 +445,7 @@
                 for (int i = 0; i < cpMap.length; i++) {
                     int x = cp_Float.getInt();
                     float fx = Float.intBitsToFloat(x);
-                    cpMap[i] = ConstantPool.getLiteralEntry(new Float(fx));
+                    cpMap[i] = ConstantPool.getLiteralEntry(fx);
                 }
                 cp_Float.doneDisbursing();
                 break;
@@ -444,7 +461,7 @@
                     long hi = cp_Long_hi.getInt();
                     long lo = cp_Long_lo.getInt();
                     long x = (hi << 32) + ((lo << 32) >>> 32);
-                    cpMap[i] = ConstantPool.getLiteralEntry(new Long(x));
+                    cpMap[i] = ConstantPool.getLiteralEntry(x);
                 }
                 cp_Long_hi.doneDisbursing();
                 cp_Long_lo.doneDisbursing();
@@ -462,7 +479,7 @@
                     long lo = cp_Double_lo.getInt();
                     long x = (hi << 32) + ((lo << 32) >>> 32);
                     double dx = Double.longBitsToDouble(x);
-                    cpMap[i] = ConstantPool.getLiteralEntry(new Double(dx));
+                    cpMap[i] = ConstantPool.getLiteralEntry(dx);
                 }
                 cp_Double_hi.doneDisbursing();
                 cp_Double_lo.doneDisbursing();
@@ -645,7 +662,7 @@
         cp_Utf8_big_suffix.doneDisbursing();
     }
 
-    HashMap utf8Signatures;  // Utf8Entry->SignatureEntry
+    Map<Utf8Entry, SignatureEntry> utf8Signatures;
 
     void readSignatureBands(Entry[] cpMap) throws IOException {
         //  cp_Signature:
@@ -663,7 +680,7 @@
         cp_Signature_classes.expectLength(getIntTotal(numSigClasses));
         cp_Signature_classes.readFrom(in);
         cp_Signature_classes.setIndex(getCPIndex(CONSTANT_Class));
-        utf8Signatures = new HashMap();
+        utf8Signatures = new HashMap<>();
         for (int i = 0; i < cpMap.length; i++) {
             Utf8Entry formRef = (Utf8Entry) cp_Signature_form.getRef();
             ClassEntry[] classRefs = new ClassEntry[numSigClasses[i]];
@@ -863,7 +880,7 @@
         ic_name.expectLength(longICCount);
         ic_name.readFrom(in);
         ic_flags.resetForSecondPass();
-        ArrayList icList = new ArrayList(numInnerClasses);
+        List<InnerClass> icList = new ArrayList<>(numInnerClasses);
         for (int i = 0; i < numInnerClasses; i++) {
             int flags = ic_flags.getInt();
             boolean longForm = (flags & ACC_IC_LONG_FORM) != 0;
@@ -876,7 +893,7 @@
                 thisName   = (Utf8Entry)  ic_name.getRef();
             } else {
                 String n = thisClass.stringValue();
-                String[] parse = pkg.parseInnerClassName(n);
+                String[] parse = Package.parseInnerClassName(n);
                 assert(parse != null);
                 String pkgOuter = parse[0];
                 //String number = parse[1];
@@ -905,7 +922,7 @@
 
     void readLocalInnerClasses(Class cls) throws IOException {
         int nc = class_InnerClasses_N.getInt();
-        ArrayList localICs = new ArrayList(nc);
+        List<InnerClass> localICs = new ArrayList<>(nc);
         for (int i = 0; i < nc; i++) {
             ClassEntry thisClass = (ClassEntry) class_InnerClasses_RC.getRef();
             int        flags     =              class_InnerClasses_F.getInt();
@@ -994,10 +1011,8 @@
         return -1;
     }
 
-    Comparator entryOutputOrder = new Comparator() {
-        public int compare(Object o0, Object o1) {
-            Entry e0 = (Entry) o0;
-            Entry e1 = (Entry) o1;
+    Comparator<Entry> entryOutputOrder = new Comparator<>() {
+        public int compare(Entry  e0, Entry e1) {
             int k0 = getOutputIndex(e0);
             int k1 = getOutputIndex(e1);
             if (k0 >= 0 && k1 >= 0)
@@ -1034,9 +1049,8 @@
     }
 
     Entry[] reconstructLocalCPMap(Class cls) {
-        HashSet ldcRefs = (HashSet) ldcRefMap.get(cls);
-        HashSet cpRefs = new HashSet();
-        HashSet sigSet = new HashSet();
+        Set<Entry> ldcRefs = ldcRefMap.get(cls);
+        Set<Entry> cpRefs = new HashSet<>();
 
         // look for constant pool entries:
         cls.visitRefs(VRM_CLASSIC, cpRefs);
@@ -1064,8 +1078,7 @@
 
         // construct a local constant pool
         int numDoubles = 0;
-        for (Iterator i = cpRefs.iterator(); i.hasNext(); ) {
-            Entry e = (Entry) i.next();
+        for (Entry e : cpRefs) {
             if (e.isDoubleWord())  numDoubles++;
             assert(e.tag != CONSTANT_Signature) : (e);
         }
@@ -1075,8 +1088,7 @@
         // Add all ldc operands first.
         if (ldcRefs != null) {
             assert(cpRefs.containsAll(ldcRefs));
-            for (Iterator i = ldcRefs.iterator(); i.hasNext(); ) {
-                Entry e = (Entry) i.next();
+            for (Entry e : ldcRefs) {
                 cpMap[fillp++] = e;
             }
             assert(fillp == 1+ldcRefs.size());
@@ -1085,11 +1097,10 @@
         }
 
         // Next add all the two-byte references.
-        HashSet wideRefs = cpRefs;
+        Set<Entry> wideRefs = cpRefs;
         cpRefs = null;  // do not use!
         int narrowLimit = fillp;
-        for (Iterator i = wideRefs.iterator(); i.hasNext(); ) {
-            Entry e = (Entry) i.next();
+        for (Entry e : wideRefs) {
             cpMap[fillp++] = e;
         }
         assert(fillp == narrowLimit+wideRefs.size());
@@ -1144,7 +1155,7 @@
         method_descr.expectLength(totalNM);
         if (verbose > 1)  Utils.log.fine("expecting #fields="+totalNF+" and #methods="+totalNM+" in #classes="+numClasses);
 
-        ArrayList fields = new ArrayList(totalNF);
+        List<Class.Field> fields = new ArrayList<>(totalNF);
         field_descr.readFrom(in);
         for (int i = 0; i < classes.length; i++) {
             Class c = classes[i];
@@ -1160,7 +1171,7 @@
         countAndReadAttrs(ATTR_CONTEXT_FIELD, fields);
         fields = null;  // release to GC
 
-        ArrayList methods = new ArrayList(totalNM);
+        List<Class.Method> methods = new ArrayList<>(totalNM);
         method_descr.readFrom(in);
         for (int i = 0; i < classes.length; i++) {
             Class c = classes[i];
@@ -1182,13 +1193,12 @@
     }
 
     Code[] allCodes;
-    List codesWithFlags;
-    HashMap ldcRefMap = new HashMap();  // HashMap<Class, HashSet<Entry>>
+    List<Code> codesWithFlags;
+    Map<Class, Set<Entry>> ldcRefMap = new HashMap<>();
 
-    Code[] buildCodeAttrs(List methods) {
-        ArrayList codes = new ArrayList(methods.size());
-        for (Iterator i = methods.iterator(); i.hasNext(); ) {
-            Class.Method m = (Class.Method) i.next();
+    Code[] buildCodeAttrs(List<Class.Method> methods) {
+        List<Code> codes = new ArrayList<>(methods.size());
+        for (Class.Method m : methods) {
             if (m.getAttribute(attrCodeEmpty) != null) {
                 m.code = new Code(m);
                 codes.add(m.code);
@@ -1211,7 +1221,7 @@
         boolean attrsOK = testBit(archiveOptions, AO_HAVE_ALL_CODE_FLAGS);
         code_headers.expectLength(allCodes.length);
         code_headers.readFrom(in);
-        ArrayList longCodes = new ArrayList(allCodes.length / 10);
+        List<Code> longCodes = new ArrayList<>(allCodes.length / 10);
         for (int i = 0; i < allCodes.length; i++) {
             Code c = allCodes[i];
             int sc = code_headers.getByte();
@@ -1238,8 +1248,7 @@
         code_max_stack.readFrom(in);
         code_max_na_locals.readFrom(in);
         code_handler_count.readFrom(in);
-        for (Iterator i = longCodes.iterator(); i.hasNext(); ) {
-            Code c = (Code) i.next();
+        for (Code c : longCodes) {
             c.setMaxStack(     code_max_stack.getInt() );
             c.setMaxNALocals(  code_max_na_locals.getInt() );
             c.setHandlerCount( code_handler_count.getInt() );
@@ -1386,8 +1395,9 @@
 
         // Fetch the attribute layout definitions which govern the bands
         // we are about to read.
-        Attribute.Layout[] defs = new Attribute.Layout[attrDefs[ctype].size()];
-        attrDefs[ctype].toArray(defs);
+        List<Attribute.Layout> defList = attrDefs.get(ctype);
+        Attribute.Layout[] defs = new Attribute.Layout[defList.size()];
+        defList.toArray(defs);
         IntBand xxx_flags_hi = getAttrBand(xxx_attr_bands, AB_FLAGS_HI);
         IntBand xxx_flags_lo = getAttrBand(xxx_attr_bands, AB_FLAGS_LO);
         IntBand xxx_attr_count = getAttrBand(xxx_attr_bands, AB_ATTR_COUNT);
@@ -1450,7 +1460,7 @@
                 bits -= (1L<<ai);
                 nfa += 1;
             }
-            ArrayList ha = new ArrayList(nfa + noa);
+            List<Attribute> ha = new ArrayList<>(nfa + noa);
             h.attributes = ha;
             bits = attrBits;  // iterate again
             for (int ai = 0; bits != 0; ai++) {
@@ -1516,7 +1526,7 @@
                 if (predef != isPredefinedAttr(ctype, ai))
                     continue;  // wrong pass
                 int totalCount = totalCounts[ai];
-                Band[] ab = (Band[]) attrBandTable.get(def);
+                Band[] ab = attrBandTable.get(def);
                 if (def == attrInnerClassesEmpty) {
                     // Special case.
                     // Size the bands as if using the following layout:
@@ -1571,15 +1581,16 @@
                                    ATTR_CONTEXT_NAME[ctype]+" attribute");
     }
 
+    @SuppressWarnings("unchecked")
     void readAttrs(int ctype, Collection holders) throws IOException {
         // Decode band values into attributes.
-        HashSet sawDefs = new HashSet();
+        Set<Attribute.Layout> sawDefs = new HashSet<>();
         ByteArrayOutputStream buf = new ByteArrayOutputStream();
         for (Iterator i = holders.iterator(); i.hasNext(); ) {
             final Attribute.Holder h = (Attribute.Holder) i.next();
             if (h.attributes == null)  continue;
-            for (ListIterator j = h.attributes.listIterator(); j.hasNext(); ) {
-                Attribute a = (Attribute) j.next();
+            for (ListIterator<Attribute> j = h.attributes.listIterator(); j.hasNext(); ) {
+                Attribute a = j.next();
                 Attribute.Layout def = a.layout();
                 if (def.bandCount == 0) {
                     if (def == attrInnerClassesEmpty) {
@@ -1595,7 +1606,7 @@
                 if (isCV)  setConstantValueIndex((Class.Field)h);
                 if (verbose > 2)
                     Utils.log.fine("read "+a+" in "+h);
-                final Band[] ab = (Band[]) attrBandTable.get(def);
+                final Band[] ab = attrBandTable.get(def);
                 // Read one attribute of type def from ab into a byte array.
                 buf.reset();
                 Object fixups = a.unparse(new Attribute.ValueStream() {
@@ -1617,10 +1628,9 @@
         }
 
         // Mark the bands we just used as done disbursing.
-        for (Iterator i = sawDefs.iterator(); i.hasNext(); ) {
-            Attribute.Layout def = (Attribute.Layout) i.next();
+        for (Attribute.Layout def : sawDefs) {
             if (def == null)  continue;  // unused index
-            Band[] ab = (Band[]) attrBandTable.get(def);
+            Band[] ab = attrBandTable.get(def);
             for (int j = 0; j < ab.length; j++) {
                 ab[j].doneDisbursing();
             }
@@ -1778,7 +1788,7 @@
         // scratch buffer for collecting code::
         byte[] buf = new byte[1<<12];
         // record of all switch opcodes (these are variable-length)
-        ArrayList allSwitchOps = new ArrayList();
+        List<Integer> allSwitchOps = new ArrayList<>();
         for (int k = 0; k < allCodes.length; k++) {
             Code c = allCodes[k];
         scanOneMethod:
@@ -1798,7 +1808,7 @@
                 case _tableswitch:
                 case _lookupswitch:
                     bc_case_count.expectMoreLength(1);
-                    allSwitchOps.add(new Integer(bc));
+                    allSwitchOps.add(bc);
                     break;
                 case _iinc:
                     bc_local.expectMoreLength(1);
@@ -1866,8 +1876,8 @@
 
         // To size instruction bands correctly, we need info on switches:
         bc_case_count.readFrom(in);
-        for (Iterator i = allSwitchOps.iterator(); i.hasNext(); ) {
-            int bc = ((Integer)i.next()).intValue();
+        for (Integer i : allSwitchOps) {
+            int bc = i.intValue();
             int caseCount = bc_case_count.getInt();
             bc_label.expectMoreLength(1+caseCount); // default label + cases
             bc_case_value.expectMoreLength(bc == _tableswitch ? 1 : caseCount);
@@ -1892,9 +1902,9 @@
 
             Class curClass = code.thisClass();
 
-            HashSet ldcRefSet = (HashSet) ldcRefMap.get(curClass);
+            Set<Entry> ldcRefSet = ldcRefMap.get(curClass);
             if (ldcRefSet == null)
-                ldcRefMap.put(curClass, ldcRefSet = new HashSet());
+                ldcRefMap.put(curClass, ldcRefSet = new HashSet<>());
 
             ClassEntry thisClass  = curClass.thisClass;
             ClassEntry superClass = curClass.superClass;
diff --git a/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java b/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java
index 82de6ac..8220e11 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java
@@ -45,10 +45,10 @@
 import java.util.Comparator;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.List;
-import java.util.ListIterator;
 import java.util.Map;
+import java.util.Set;
+import static com.sun.java.util.jar.pack.Constants.*;
 
 /**
  * Writer for a package file.
@@ -111,12 +111,12 @@
         }
     }
 
-    HashSet     requiredEntries;  // for the CP
-    HashMap     backCountTable;   // for layout callables
+    Set<Entry>                       requiredEntries;  // for the CP
+    Map<Attribute.Layout, int[]>     backCountTable;   // for layout callables
     int[][]     attrCounts;       // count attr. occurences
 
     void setup() {
-        requiredEntries = new HashSet();
+        requiredEntries = new HashSet<>();
         setArchiveOptions();
         trimClassAttributes();
         collectAttributeLayouts();
@@ -139,9 +139,7 @@
         // Import defaults from package (deflate hint, etc.).
         archiveOptions |= pkg.default_options;
 
-        for (Iterator i = pkg.files.iterator(); i.hasNext(); ) {
-            File file = (File) i.next();
-
+        for (File file : pkg.files) {
             int modtime = file.modtime;
             int options = file.options;
 
@@ -178,16 +176,15 @@
             }
         }
         // Decide on default version number (majority rule).
-        HashMap verCounts = new HashMap();
+        Map<Integer, int[]> verCounts = new HashMap<>();
         int bestCount = 0;
         int bestVersion = -1;
-        for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) {
-            Class cls = (Class) i.next();
+        for (Class cls : pkg.classes) {
             int version = cls.getVersion();
-            int[] var = (int[]) verCounts.get(new Integer(version));
+            int[] var = verCounts.get(version);
             if (var == null) {
                 var = new int[1];
-                verCounts.put(new Integer(version), var);
+                verCounts.put(version, var);
             }
             int count = (var[0] += 1);
             //System.out.println("version="+version+" count="+count);
@@ -210,9 +207,7 @@
                            Package.versionStringOf(pkg.getHighestClassVersion()));
 
         // Now add explicit pseudo-attrs. to classes with odd versions.
-        for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) {
-            Class cls = (Class) i.next();
-
+        for (Class cls : pkg.classes) {
             if (cls.getVersion() != bestVersion) {
                 Attribute a = makeClassFileVersionAttr(cls.minver, cls.majver);
                 if (verbose > 1) {
@@ -228,8 +223,7 @@
         }
 
         // Decide if we are transmitting a huge resource file:
-        for (Iterator i = pkg.files.iterator(); i.hasNext(); ) {
-            File file = (File) i.next();
+        for (File file : pkg.files) {
             long len = file.getFileLength();
             if (len != (int)len) {
                 archiveOptions |= AO_HAVE_FILE_SIZE_HI;
@@ -244,10 +238,8 @@
         // we must declare unconditional presence of code flags.
         int cost0 = 0;
         int cost1 = 0;
-        for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) {
-            Class cls = (Class) i.next();
-            for (Iterator j = cls.getMethods().iterator(); j.hasNext(); ) {
-                Class.Method m = (Class.Method) j.next();
+        for (Class cls : pkg.classes) {
+            for (Class.Method m : cls.getMethods()) {
                 if (m.code != null) {
                     if (m.code.attributeSize() == 0) {
                         // cost of a useless unconditional flags byte
@@ -352,7 +344,7 @@
             archive_header_1.putInt(pkg.default_modtime);
             archive_header_1.putInt(pkg.files.size());
         } else {
-            assert(pkg.files.size() == 0);
+            assert(pkg.files.isEmpty());
         }
 
         if (haveSpecial) {
@@ -697,8 +689,7 @@
         boolean haveModtime = testBit(options, AO_HAVE_FILE_MODTIME);
         boolean haveOptions = testBit(options, AO_HAVE_FILE_OPTIONS);
         if (!haveOptions) {
-            for (Iterator i = pkg.files.iterator(); i.hasNext(); ) {
-                File file = (File) i.next();
+            for (File file : pkg.files) {
                 if (file.isClassStub()) {
                     haveOptions = true;
                     options |= AO_HAVE_FILE_OPTIONS;
@@ -711,9 +702,7 @@
             options |= AO_HAVE_FILE_HEADERS;
             archiveOptions = options;
         }
-
-        for (Iterator i = pkg.files.iterator(); i.hasNext(); ) {
-            File file = (File) i.next();
+        for (File file : pkg.files) {
             file_name.putRef(file.name);
             long len = file.getFileLength();
             file_size_lo.putInt((int)len);
@@ -731,22 +720,20 @@
             Utils.log.info("Wrote "+numFiles+" resource files");
     }
 
+    @SuppressWarnings("unchecked")
     void collectAttributeLayouts() {
         maxFlags = new int[ATTR_CONTEXT_LIMIT];
-        allLayouts = new HashMap[ATTR_CONTEXT_LIMIT];
+        allLayouts = new FixedList<>(ATTR_CONTEXT_LIMIT);
         for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
-            allLayouts[i] = new HashMap();
+            allLayouts.set(i, new HashMap<Attribute.Layout, int[]>());
         }
         // Collect maxFlags and allLayouts.
-        for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) {
-            Class cls = (Class) i.next();
+        for (Class cls : pkg.classes) {
             visitAttributeLayoutsIn(ATTR_CONTEXT_CLASS, cls);
-            for (Iterator j = cls.getFields().iterator(); j.hasNext(); ) {
-                Class.Field f = (Class.Field) j.next();
+            for (Class.Field f : cls.getFields()) {
                 visitAttributeLayoutsIn(ATTR_CONTEXT_FIELD, f);
             }
-            for (Iterator j = cls.getMethods().iterator(); j.hasNext(); ) {
-                Class.Method m = (Class.Method) j.next();
+            for (Class.Method m : cls.getMethods()) {
                 visitAttributeLayoutsIn(ATTR_CONTEXT_METHOD, m);
                 if (m.code != null) {
                     visitAttributeLayoutsIn(ATTR_CONTEXT_CODE, m.code);
@@ -755,7 +742,7 @@
         }
         // If there are many species of attributes, use 63-bit flags.
         for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
-            int nl = allLayouts[i].size();
+            int nl = allLayouts.get(i).size();
             boolean haveLongFlags = haveFlagsHi(i);
             final int TOO_MANY_ATTRS = 32 /*int flag size*/
                 - 12 /*typical flag bits in use*/
@@ -781,7 +768,7 @@
         }
         // Collect counts for both predefs. and custom defs.
         // Decide on custom, local attribute definitions.
-        backCountTable = new HashMap();
+        backCountTable = new HashMap<>();
         attrCounts = new int[ATTR_CONTEXT_LIMIT][];
         for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
             // Now the remaining defs in allLayouts[i] need attr. indexes.
@@ -793,11 +780,12 @@
             assert(attrIndexLimit[i] < 64);  // all bits fit into a Java long
             avHiBits &= (1L<<attrIndexLimit[i])-1;
             int nextLoBit = 0;
-            Map.Entry[] layoutsAndCounts = new Map.Entry[allLayouts[i].size()];
-            allLayouts[i].entrySet().toArray(layoutsAndCounts);
+            Map<Attribute.Layout, int[]> defMap = allLayouts.get(i);
+            Map.Entry[] layoutsAndCounts = new Map.Entry[defMap.size()];
+            defMap.entrySet().toArray(layoutsAndCounts);
             // Sort by count, most frequent first.
             // Predefs. participate in this sort, though it does not matter.
-            Arrays.sort(layoutsAndCounts, new Comparator() {
+            Arrays.sort(layoutsAndCounts, new Comparator<>() {
                 public int compare(Object o0, Object o1) {
                     Map.Entry e0 = (Map.Entry) o0;
                     Map.Entry e1 = (Map.Entry) o1;
@@ -814,7 +802,7 @@
                 Attribute.Layout def = (Attribute.Layout) e.getKey();
                 int count = ((int[])e.getValue())[0];
                 int index;
-                Integer predefIndex = (Integer) attrIndexTable.get(def);
+                Integer predefIndex = attrIndexTable.get(def);
                 if (predefIndex != null) {
                     // The index is already set.
                     index = predefIndex.intValue();
@@ -872,29 +860,32 @@
 
     // Scratch variables for processing attributes and flags.
     int[] maxFlags;
-    HashMap[] allLayouts;
+    List<Map<Attribute.Layout, int[]>> allLayouts;
 
     void visitAttributeLayoutsIn(int ctype, Attribute.Holder h) {
         // Make note of which flags appear in the class file.
         // Set them in maxFlags.
         maxFlags[ctype] |= h.flags;
-        for (Iterator i = h.getAttributes().iterator(); i.hasNext(); ) {
-            Attribute a = (Attribute) i.next();
+        for (Attribute a : h.getAttributes()) {
             Attribute.Layout def = a.layout();
-            int[] count = (int[]) allLayouts[ctype].get(def);
-            if (count == null)
-                allLayouts[ctype].put(def, count = new int[1]);
-            if (count[0] < Integer.MAX_VALUE)
+            Map<Attribute.Layout, int[]> defMap = allLayouts.get(ctype);
+            int[] count = defMap.get(def);
+            if (count == null) {
+                defMap.put(def, count = new int[1]);
+            }
+            if (count[0] < Integer.MAX_VALUE) {
                 count[0] += 1;
+            }
         }
     }
 
     Attribute.Layout[] attrDefsWritten;
 
+    @SuppressWarnings("unchecked")
     void writeAttrDefs() throws IOException {
-        ArrayList defList = new ArrayList();
+        List<Object[]> defList = new ArrayList<>();
         for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
-            int limit = attrDefs[i].size();
+            int limit = attrDefs.get(i).size();
             for (int j = 0; j < limit; j++) {
                 int header = i;  // ctype
                 if (j < attrIndexLimit[i]) {
@@ -906,9 +897,9 @@
                         continue;
                     }
                 }
-                Attribute.Layout def = (Attribute.Layout) attrDefs[i].get(j);
-                defList.add(new Object[]{ new Integer(header), def });
-                assert(new Integer(j).equals(attrIndexTable.get(def)));
+                Attribute.Layout def = attrDefs.get(i).get(j);
+                defList.add(new Object[]{ Integer.valueOf(header), def });
+                assert(Integer.valueOf(j).equals(attrIndexTable.get(def)));
             }
         }
         // Sort the new attr defs into some "natural" order.
@@ -934,10 +925,7 @@
         attrDefsWritten = new Attribute.Layout[numAttrDefs];
         PrintStream dump = !optDumpBands ? null
             : new PrintStream(getDumpStream(attr_definition_headers, ".def"));
-        int[] indexForDebug = new int[ATTR_CONTEXT_LIMIT];
-        for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
-            indexForDebug[i] = attrIndexLimit[i];
-        }
+        int[] indexForDebug = Arrays.copyOf(attrIndexLimit, ATTR_CONTEXT_LIMIT);
         for (int i = 0; i < defs.length; i++) {
             int header = ((Integer)defs[i][0]).intValue();
             Attribute.Layout def = (Attribute.Layout) defs[i][1];
@@ -953,7 +941,7 @@
             if (debug) {
                 int hdrIndex = (header >> ADH_BIT_SHIFT) - ADH_BIT_IS_LSB;
                 if (hdrIndex < 0)  hdrIndex = indexForDebug[def.ctype()]++;
-                int realIndex = ((Integer) attrIndexTable.get(def)).intValue();
+                int realIndex = (attrIndexTable.get(def)).intValue();
                 assert(hdrIndex == realIndex);
             }
             if (dump != null) {
@@ -969,8 +957,8 @@
         for (int ctype = 0; ctype < ATTR_CONTEXT_LIMIT; ctype++) {
             MultiBand xxx_attr_bands = attrBands[ctype];
             IntBand xxx_attr_calls = getAttrBand(xxx_attr_bands, AB_ATTR_CALLS);
-            Attribute.Layout[] defs = new Attribute.Layout[attrDefs[ctype].size()];
-            attrDefs[ctype].toArray(defs);
+            Attribute.Layout[] defs = new Attribute.Layout[attrDefs.get(ctype).size()];
+            attrDefs.get(ctype).toArray(defs);
             for (boolean predef = true; ; predef = false) {
                 for (int ai = 0; ai < defs.length; ai++) {
                     Attribute.Layout def = defs[ai];
@@ -980,7 +968,7 @@
                     int totalCount = attrCounts[ctype][ai];
                     if (totalCount == 0)
                         continue;  // irrelevant
-                    int[] bc = (int[]) backCountTable.get(def);
+                    int[] bc = backCountTable.get(def);
                     for (int j = 0; j < bc.length; j++) {
                         if (bc[j] >= 0) {
                             int backCount = bc[j];
@@ -998,8 +986,7 @@
     }
 
     void trimClassAttributes() {
-        for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) {
-            Class cls = (Class) i.next();
+        for (Class cls : pkg.classes) {
             // Replace "obvious" SourceFile attrs by null.
             cls.minimizeSourceFile();
         }
@@ -1008,14 +995,12 @@
     void collectInnerClasses() {
         // Capture inner classes, removing them from individual classes.
         // Irregular inner classes must stay local, though.
-        HashMap allICMap = new HashMap();
+        Map<ClassEntry, InnerClass> allICMap = new HashMap<>();
         // First, collect a consistent global set.
-        for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) {
-            Class cls = (Class) i.next();
+        for (Class cls : pkg.classes) {
             if (!cls.hasInnerClasses())  continue;
-            for (Iterator j = cls.getInnerClasses().iterator(); j.hasNext(); ) {
-                InnerClass ic = (InnerClass) j.next();
-                InnerClass pic = (InnerClass) allICMap.put(ic.thisClass, ic);
+            for (InnerClass ic : cls.getInnerClasses()) {
+                InnerClass pic = allICMap.put(ic.thisClass, ic);
                 if (pic != null && !pic.equals(ic) && pic.predictable) {
                     // Different ICs.  Choose the better to make global.
                     allICMap.put(pic.thisClass, pic);
@@ -1036,15 +1021,13 @@
         // Next, empty out of every local set the consistent entries.
         // Calculate whether there is any remaining need to have a local
         // set, and whether it needs to be locked.
-        for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) {
-            Class cls = (Class) i.next();
+        for (Class cls : pkg.classes) {
             cls.minimizeLocalICs();
         }
     }
 
     void writeInnerClasses() throws IOException {
-        for (Iterator i = pkg.getAllInnerClasses().iterator(); i.hasNext(); ) {
-            InnerClass ic = (InnerClass) i.next();
+        for (InnerClass ic : pkg.getAllInnerClasses()) {
             int flags = ic.flags;
             assert((flags & ACC_IC_LONG_FORM) == 0);
             if (!ic.predictable) {
@@ -1064,10 +1047,9 @@
      *  local attribute.  This is expected to be rare.
      */
     void writeLocalInnerClasses(Class cls) throws IOException {
-        List localICs = cls.getInnerClasses();
+        List<InnerClass> localICs = cls.getInnerClasses();
         class_InnerClasses_N.putInt(localICs.size());
-        for (Iterator i = localICs.iterator(); i.hasNext(); ) {
-            InnerClass ic = (InnerClass) i.next();
+        for(InnerClass ic : localICs) {
             class_InnerClasses_RC.putRef(ic.thisClass);
             // Is it redundant with the global version?
             if (ic.equals(pkg.getGlobalInnerClass(ic.thisClass))) {
@@ -1121,18 +1103,16 @@
     }
 
     void writeMembers(Class cls) throws IOException {
-        List fields = cls.getFields();
+        List<Class.Field> fields = cls.getFields();
         class_field_count.putInt(fields.size());
-        for (Iterator i = fields.iterator(); i.hasNext(); ) {
-            Class.Field f = (Class.Field) i.next();
+        for (Class.Field f : fields) {
             field_descr.putRef(f.getDescriptor());
             writeAttrs(ATTR_CONTEXT_FIELD, f, cls);
         }
 
-        List methods = cls.getMethods();
+        List<Class.Method> methods = cls.getMethods();
         class_method_count.putInt(methods.size());
-        for (Iterator i = methods.iterator(); i.hasNext(); ) {
-            Class.Method m = (Class.Method) i.next();
+        for (Class.Method m : methods) {
             method_descr.putRef(m.getDescriptor());
             writeAttrs(ATTR_CONTEXT_METHOD, m, cls);
             assert((m.code != null) == (m.getAttribute(attrCodeEmpty) != null));
@@ -1206,11 +1186,10 @@
         long flagMask = attrFlagMask[ctype];  // which flags are attr bits?
         long flagsToAdd = 0;
         int overflowCount = 0;
-        for (ListIterator j = h.attributes.listIterator(); j.hasNext(); ) {
-            Attribute a = (Attribute) j.next();
+        for (Attribute a : h.attributes) {
             Attribute.Layout def = a.layout();
-            int index = ((Integer)attrIndexTable.get(def)).intValue();
-            assert(attrDefs[ctype].get(index) == def);
+            int index = (attrIndexTable.get(def)).intValue();
+            assert(attrDefs.get(ctype).get(index) == def);
             if (verbose > 3)
                 Utils.log.fine("add attr @"+index+" "+a+" in "+h);
             if (index < attrIndexLimit[ctype] && testBit(flagMask, 1L<<index)) {
@@ -1239,10 +1218,10 @@
                 continue;
             }
             assert(a.fixups == null);
-            final Band[] ab = (Band[]) attrBandTable.get(def);
+            final Band[] ab = attrBandTable.get(def);
             assert(ab != null);
             assert(ab.length == def.bandCount);
-            final int[] bc = (int[]) backCountTable.get(def);
+            final int[] bc = backCountTable.get(def);
             assert(bc != null);
             assert(bc.length == def.getCallables().length);
             // Write one attribute of type def into ab.
@@ -1306,7 +1285,7 @@
     private int initOpVariant(Instruction i, Entry newClass) {
         if (i.getBC() != _invokespecial)  return -1;
         MemberEntry ref = (MemberEntry) i.getCPRef(curCPMap);
-        if (ref.descRef.nameRef.stringValue() != "<init>")
+        if ("<init>".equals(ref.descRef.nameRef.stringValue()) == false)
             return -1;
         ClassEntry refClass = ref.classRef;
         if (refClass == curClass.thisClass)
@@ -1618,14 +1597,16 @@
             String count = "" + codeHist[bc];
             count = "         ".substring(count.length()) + count;
             String pct = "" + (codeHist[bc] * 10000 / totalBytes);
-            while (pct.length() < 4)  pct = "0" + pct;
+            while (pct.length() < 4) {
+                pct = "0" + pct;
+            }
             pct = pct.substring(0, pct.length()-2) + "." + pct.substring(pct.length()-2);
             hist[bc] = count + "  " + pct + "%  " + iname;
         }
         Arrays.sort(hist);
         System.out.println("Bytecode histogram ["+totalBytes+"]");
         for (int i = hist.length; --i >= 0; ) {
-            if (hist[i] == "")  continue;
+            if ("".equals(hist[i]))  continue;
             System.out.println(hist[i]);
         }
         for (int tag = 0; tag < ldcHist.length; tag++) {
diff --git a/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java b/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java
index 7e2f6a2..aefac52 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java
@@ -69,7 +69,8 @@
      * Get the set of options for the pack and unpack engines.
      * @return A sorted association of option key strings to option values.
      */
-    public SortedMap<String, String> properties() {
+    @SuppressWarnings("unchecked")
+    public SortedMap properties() {
         return props;
     }
 
@@ -155,8 +156,8 @@
 
 
     // All the worker bees.....
-
     // The packer worker.
+    @SuppressWarnings("unchecked")
     private class DoPack {
         final int verbose = props.getInteger(Utils.DEBUG_VERBOSE);
 
@@ -179,11 +180,11 @@
             unknownAttrCommand = uaMode.intern();
         }
 
-        final HashMap attrDefs;
-        final HashMap attrCommands;
+        final Map<Attribute.Layout, Attribute> attrDefs;
+        final Map<Attribute.Layout, String> attrCommands;
         {
-            HashMap attrDefs     = new HashMap();
-            HashMap attrCommands = new HashMap();
+            Map<Attribute.Layout, Attribute> lattrDefs   = new HashMap<>();
+            Map<Attribute.Layout, String>  lattrCommands = new HashMap<>();
             String[] keys = {
                 Pack200.Packer.CLASS_ATTRIBUTE_PFX,
                 Pack200.Packer.FIELD_ATTRIBUTE_PFX,
@@ -198,8 +199,9 @@
             };
             for (int i = 0; i < ctypes.length; i++) {
                 String pfx = keys[i];
-                Map<String, String> map = props.prefixMap(pfx);
-                for (String key : map.keySet()) {
+                Map<Object, Object> map = props.prefixMap(pfx);
+                for (Object k : map.keySet()) {
+                    String key = (String)k;
                     assert(key.startsWith(pfx));
                     String name = key.substring(pfx.length());
                     String layout = props.getProperty(key);
@@ -207,24 +209,18 @@
                     if (Pack200.Packer.STRIP.equals(layout) ||
                         Pack200.Packer.PASS.equals(layout) ||
                         Pack200.Packer.ERROR.equals(layout)) {
-                        attrCommands.put(lkey, layout.intern());
+                        lattrCommands.put(lkey, layout.intern());
                     } else {
-                        Attribute.define(attrDefs, ctypes[i], name, layout);
+                        Attribute.define(lattrDefs, ctypes[i], name, layout);
                         if (verbose > 1) {
                             Utils.log.fine("Added layout for "+Constants.ATTR_CONTEXT_NAME[i]+" attribute "+name+" = "+layout);
                         }
-                        assert(attrDefs.containsKey(lkey));
+                        assert(lattrDefs.containsKey(lkey));
                     }
                 }
             }
-            if (attrDefs.size() > 0)
-                this.attrDefs = attrDefs;
-            else
-                this.attrDefs = null;
-            if (attrCommands.size() > 0)
-                this.attrCommands = attrCommands;
-            else
-                this.attrCommands = null;
+            this.attrDefs = (lattrDefs.isEmpty()) ? null : lattrDefs;
+            this.attrCommands = (lattrCommands.isEmpty()) ? null : lattrCommands;
         }
 
         final boolean keepFileOrder
@@ -275,8 +271,8 @@
         {
             // Which class files will be passed through?
             passFiles = props.getProperties(Pack200.Packer.PASS_FILE_PFX);
-            for (ListIterator i = passFiles.listIterator(); i.hasNext(); ) {
-                String file = (String) i.next();
+            for (ListIterator<String> i = passFiles.listIterator(); i.hasNext(); ) {
+                String file = i.next();
                 if (file == null) { i.remove(); continue; }
                 file = Utils.getJarEntryName(file);  // normalize '\\' to '/'
                 if (file.endsWith("/"))
@@ -333,7 +329,7 @@
             pkg.reset();
         }
 
-        class InFile {
+        final class InFile {
             final String name;
             final JarFile jf;
             final JarEntry je;
@@ -596,8 +592,8 @@
                 // Package builder must have created a stub for each class.
                 assert(pkg.files.containsAll(pkg.getClassStubs()));
                 // Order of stubs in file list must agree with classes.
-                List res = pkg.files;
-                assert((res = new ArrayList(pkg.files))
+                List<Package.File> res = pkg.files;
+                assert((res = new ArrayList<>(pkg.files))
                        .retainAll(pkg.getClassStubs()) || true);
                 assert(res.equals(pkg.getClassStubs()));
             }
diff --git a/src/share/classes/com/sun/java/util/jar/pack/PopulationCoding.java b/src/share/classes/com/sun/java/util/jar/pack/PopulationCoding.java
index 1e7f9bb..d20f5e4 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/PopulationCoding.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/PopulationCoding.java
@@ -31,6 +31,8 @@
 import java.io.OutputStream;
 import java.util.Arrays;
 import java.util.HashSet;
+import java.util.Set;
+import static com.sun.java.util.jar.pack.Constants.*;
 
 /**
  * Population-based coding.
@@ -38,7 +40,7 @@
  * @author John Rose
  */
 // This tactic alone reduces the final zipped rt.jar by about a percent.
-class PopulationCoding implements Constants, CodingMethod {
+class PopulationCoding implements CodingMethod {
     Histogram vHist;   // histogram of all values
     int[]     fValues; // list of favored values
     int       fVlen;   // inclusive max index
@@ -62,8 +64,8 @@
         }
     }
     public void setFavoredValues(int[] fValues) {
-        int fVlen = fValues.length-1;
-        setFavoredValues(fValues, fVlen);
+        int lfVlen = fValues.length-1;
+        setFavoredValues(fValues, lfVlen);
     }
     public void setHistogram(Histogram vHist) {
         this.vHist = vHist;
@@ -103,7 +105,7 @@
         if (tokenCoding instanceof Coding && fValues != null) {
             Coding tc = (Coding) tokenCoding;
             if (tc == fitTokenCoding(fVlen, tc.L()))
-                this.L = tc.L();;
+                this.L = tc.L();
             // Otherwise, it's a non-default coding.
         }
     }
@@ -217,13 +219,13 @@
     }
 
     private long[] makeSymtab() {
-        long[] symtab = new long[fVlen];
+        long[] lsymtab = new long[fVlen];
         for (int token = 1; token <= fVlen; token++) {
-            symtab[token-1] = ((long)fValues[token] << 32) | token;
+            lsymtab[token-1] = ((long)fValues[token] << 32) | token;
         }
         // Index by value:
-        Arrays.sort(symtab);
-        return symtab;
+        Arrays.sort(lsymtab);
+        return lsymtab;
     }
 
     private Coding getTailCoding(CodingMethod c) {
@@ -302,12 +304,12 @@
     }
 
     int[] readFavoredValuesFrom(InputStream in, int maxForDebug) throws IOException {
-        int[] fValues = new int[1000];  // realloc as needed
+        int[] lfValues = new int[1000];  // realloc as needed
         // The set uniqueValuesForDebug records all favored values.
         // As each new value is added, we assert that the value
         // was not already in the set.
-        HashSet uniqueValuesForDebug = null;
-        assert((uniqueValuesForDebug = new HashSet()) != null);
+        Set<Integer> uniqueValuesForDebug = null;
+        assert((uniqueValuesForDebug = new HashSet<>()) != null);
         int fillp = 1;
         maxForDebug += fillp;
         int min = Integer.MIN_VALUE;  // farthest from the center
@@ -317,13 +319,14 @@
         while (fcm instanceof AdaptiveCoding) {
             AdaptiveCoding ac = (AdaptiveCoding) fcm;
             int len = ac.headLength;
-            while (fillp + len > fValues.length)
-                fValues = BandStructure.realloc(fValues);
+            while (fillp + len > lfValues.length) {
+                lfValues = BandStructure.realloc(lfValues);
+            }
             int newFillp = fillp + len;
-            ac.headCoding.readArrayFrom(in, fValues, fillp, newFillp);
+            ac.headCoding.readArrayFrom(in, lfValues, fillp, newFillp);
             while (fillp < newFillp) {
-                int val = fValues[fillp++];
-                assert(uniqueValuesForDebug.add(new Integer(val)));
+                int val = lfValues[fillp++];
+                assert(uniqueValuesForDebug.add(val));
                 assert(fillp <= maxForDebug);
                 last = val;
                 min = moreCentral(min, val);
@@ -344,10 +347,10 @@
                 state = val;
                 if (fillp > 1 && (val == last || val == min)) //|| val == min2
                     break;
-                if (fillp == fValues.length)
-                    fValues = BandStructure.realloc(fValues);
-                fValues[fillp++] = val;
-                assert(uniqueValuesForDebug.add(new Integer(val)));
+                if (fillp == lfValues.length)
+                    lfValues = BandStructure.realloc(lfValues);
+                lfValues[fillp++] = val;
+                assert(uniqueValuesForDebug.add(val));
                 assert(fillp <= maxForDebug);
                 last = val;
                 min = moreCentral(min, val);
@@ -358,17 +361,17 @@
                 int val = fc.readFrom(in);
                 if (fillp > 1 && (val == last || val == min)) //|| val == min2
                     break;
-                if (fillp == fValues.length)
-                    fValues = BandStructure.realloc(fValues);
-                fValues[fillp++] = val;
-                assert(uniqueValuesForDebug.add(new Integer(val)));
+                if (fillp == lfValues.length)
+                    lfValues = BandStructure.realloc(lfValues);
+                lfValues[fillp++] = val;
+                assert(uniqueValuesForDebug.add(val));
                 assert(fillp <= maxForDebug);
                 last = val;
                 min = moreCentral(min, val);
                 //min2 = moreCentral2(min2, val, min);
             }
         }
-        return BandStructure.realloc(fValues, fillp);
+        return BandStructure.realloc(lfValues, fillp);
     }
 
     private static int moreCentral(int x, int y) {
@@ -478,7 +481,7 @@
         boolean verbose
             = (p200 != null &&
                p200.getBoolean(Utils.COM_PREFIX+"verbose.pop"));
-        StringBuffer res = new StringBuffer(100);
+        StringBuilder res = new StringBuilder(100);
         res.append("pop(").append("fVlen=").append(fVlen);
         if (verbose && fValues != null) {
             res.append(" fV=[");
diff --git a/src/share/classes/com/sun/java/util/jar/pack/PropMap.java b/src/share/classes/com/sun/java/util/jar/pack/PropMap.java
index 3072ef3..afed905 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/PropMap.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/PropMap.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003,2010 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -34,8 +34,8 @@
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Comparator;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
@@ -46,36 +46,36 @@
 /**
  * Control block for publishing Pack200 options to the other classes.
  */
-class PropMap extends TreeMap {
-    ArrayList _listeners = new ArrayList(1);
+
+final class PropMap implements SortedMap<Object, Object>  {
+    private final TreeMap<Object, Object> theMap = new TreeMap<>();;
+    private final List<PropertyChangeListener> listenerList = new ArrayList<>(1);
 
     void addListener(PropertyChangeListener listener) {
-        _listeners.add(listener);
+        listenerList.add(listener);
     }
 
     void removeListener(PropertyChangeListener listener) {
-        _listeners.remove(listener);
+        listenerList.remove(listener);
     }
 
-    void addListeners(ArrayList listeners) {
-        _listeners.addAll(listeners);
+    void addListeners(ArrayList<PropertyChangeListener> listeners) {
+        listenerList.addAll(listeners);
     }
 
-    void removeListeners(ArrayList listeners) {
-        _listeners.removeAll(listeners);
+    void removeListeners(ArrayList<PropertyChangeListener> listeners) {
+        listenerList.removeAll(listeners);
     }
 
     // Override:
     public Object put(Object key, Object value) {
-        Object oldValue = super.put(key, value);
-        if (value != oldValue && _listeners.size() > 0) {
+        Object oldValue = theMap.put(key, value);
+        if (value != oldValue && !listenerList.isEmpty()) {
             // Post the property change event.
             PropertyChangeEvent event =
                 new PropertyChangeEvent(this, (String) key,
                                         oldValue, value);
-            for (Iterator i = _listeners.iterator(); i.hasNext(); ) {
-                PropertyChangeListener listener =
-                    (PropertyChangeListener) i.next();
+            for (PropertyChangeListener listener : listenerList) {
                 listener.propertyChange(event);
             }
         }
@@ -85,7 +85,7 @@
     // All this other stuff is private to the current package.
     // Outide clients of Pack200 do not need to use it; they can
     // get by with generic SortedMap functionality.
-    private static Map defaultProps;
+    private static Map<Object, Object> defaultProps;
     static {
         Properties props = new Properties();
 
@@ -122,13 +122,12 @@
         // Define certain attribute layouts by default.
         // Do this after the previous props are put in place,
         // to allow override if necessary.
+        InputStream propStr = null;
         try {
             String propFile = "intrinsic.properties";
-            InputStream propStr = PackerImpl.class.getResourceAsStream(propFile);
+            propStr = PackerImpl.class.getResourceAsStream(propFile);
             props.load(new BufferedInputStream(propStr));
-            propStr.close();
-            for (Iterator i = props.entrySet().iterator(); i.hasNext(); ) {
-                Map.Entry e = (Map.Entry) i.next();
+            for (Map.Entry<Object, Object> e : props.entrySet()) {
                 String key = (String) e.getKey();
                 String val = (String) e.getValue();
                 if (key.startsWith("attribute.")) {
@@ -137,19 +136,25 @@
             }
         } catch (IOException ee) {
             throw new RuntimeException(ee);
+        } finally {
+            try {
+                if (propStr != null) {
+                    propStr.close();
+                }
+            } catch (IOException ignore) {}
         }
 
-        defaultProps = (new HashMap(props));  // shrink to fit
+        defaultProps = (new HashMap<>(props));  // shrink to fit
     }
 
     PropMap() {
-        putAll(defaultProps);
+        theMap.putAll(defaultProps);
     }
 
     // Return a view of this map which includes only properties
     // that begin with the given prefix.  This is easy because
     // the map is sorted, and has a subMap accessor.
-    SortedMap prefixMap(String prefix) {
+    SortedMap<Object, Object> prefixMap(String prefix) {
         int len = prefix.length();
         if (len == 0)
             return this;
@@ -174,8 +179,8 @@
 
     // Get sequence of props for "prefix", and "prefix.*".
     List getProperties(String prefix) {
-        Collection values = prefixMap(prefix).values();
-        ArrayList res = new ArrayList(values.size());
+        Collection<Object> values = prefixMap(prefix).values();
+        List<Object> res = new ArrayList<>(values.size());
         res.addAll(values);
         while (res.remove(null));
         return res;
@@ -240,11 +245,97 @@
     void list(PrintWriter out) {
         out.println("#"+Utils.PACK_ZIP_ARCHIVE_MARKER_COMMENT+"[");
         Set defaults = defaultProps.entrySet();
-        for (Iterator i = entrySet().iterator(); i.hasNext(); ) {
-            Map.Entry e = (Map.Entry) i.next();
+        for (Map.Entry e : theMap.entrySet()) {
             if (defaults.contains(e))  continue;
             out.println("  " + e.getKey() + " = " + e.getValue());
         }
         out.println("#]");
     }
+
+    @Override
+    public int size() {
+        return theMap.size();
+    }
+
+    @Override
+    public boolean isEmpty() {
+        return theMap.isEmpty();
+    }
+
+    @Override
+    public boolean containsKey(Object key) {
+        return theMap.containsKey(key);
+    }
+
+    @Override
+    public boolean containsValue(Object value) {
+        return theMap.containsValue(value);
+    }
+
+    @Override
+    public Object get(Object key) {
+        return theMap.get(key);
+    }
+
+    @Override
+    public Object remove(Object key) {
+       return theMap.remove(key);
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public void putAll(Map m) {
+       theMap.putAll(m);
+    }
+
+    @Override
+    public void clear() {
+        theMap.clear();
+    }
+
+    @Override
+    public Set<Object> keySet() {
+       return theMap.keySet();
+    }
+
+    @Override
+    public Collection<Object> values() {
+       return theMap.values();
+    }
+
+    @Override
+    public Set<Map.Entry<Object, Object>> entrySet() {
+        return theMap.entrySet();
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public Comparator<Object> comparator() {
+        return (Comparator<Object>) theMap.comparator();
+    }
+
+    @Override
+    public SortedMap<Object, Object> subMap(Object fromKey, Object toKey) {
+        return theMap.subMap(fromKey, toKey);
+    }
+
+    @Override
+    public SortedMap<Object, Object> headMap(Object toKey) {
+        return theMap.headMap(toKey);
+    }
+
+    @Override
+    public SortedMap<Object, Object> tailMap(Object fromKey) {
+        return theMap.tailMap(fromKey);
+    }
+
+    @Override
+    public Object firstKey() {
+        return theMap.firstKey();
+    }
+
+    @Override
+    public Object lastKey() {
+       return theMap.lastKey();
+    }
 }
diff --git a/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java b/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java
index a0c1e4d..06bec82 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java
@@ -34,7 +34,7 @@
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.util.HashSet;
-import java.util.Iterator;
+import java.util.Set;
 import java.util.SortedMap;
 import java.util.TimeZone;
 import java.util.jar.JarEntry;
@@ -81,7 +81,8 @@
      * Get the set of options for the pack and unpack engines.
      * @return A sorted association of option key strings to option values.
      */
-    public SortedMap<String, String> properties() {
+    @SuppressWarnings("unchecked")
+    public SortedMap properties() {
         return props;
     }
 
@@ -225,9 +226,8 @@
             props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"50");
             pkg.ensureAllClassFiles();
             // Now write out the files.
-            HashSet<Package.Class> classesToWrite = new HashSet<>(pkg.getClasses());
-            for (Iterator i = pkg.getFiles().iterator(); i.hasNext(); ) {
-                Package.File file = (Package.File) i.next();
+            Set<Package.Class> classesToWrite = new HashSet<>(pkg.getClasses());
+            for (Package.File file : pkg.getFiles()) {
                 String name = file.nameString;
                 JarEntry je = new JarEntry(Utils.getJarEntryName(name));
                 boolean deflate;
diff --git a/src/share/classes/com/sun/java/util/jar/pack/Utils.java b/src/share/classes/com/sun/java/util/jar/pack/Utils.java
index d14d599..4b5c4c8 100644
--- a/src/share/classes/com/sun/java/util/jar/pack/Utils.java
+++ b/src/share/classes/com/sun/java/util/jar/pack/Utils.java
@@ -297,7 +297,7 @@
             (int)( (1.0 - ((double)ze.getCompressedSize()/(double)ze.getSize()))*100 )
             : 0 ;
         // Follow unzip -lv output
-        return (long)ze.getSize() + "\t" + ze.getMethod()
+        return ze.getSize() + "\t" + ze.getMethod()
             + "\t" + ze.getCompressedSize() + "\t"
             + store + "%\t"
             + new Date(ze.getTime()) + "\t"
diff --git a/src/share/classes/com/sun/media/sound/DirectAudioDevice.java b/src/share/classes/com/sun/media/sound/DirectAudioDevice.java
index 127e7f3..57c8085 100644
--- a/src/share/classes/com/sun/media/sound/DirectAudioDevice.java
+++ b/src/share/classes/com/sun/media/sound/DirectAudioDevice.java
@@ -1393,8 +1393,11 @@
         public void run() {
             if (Printer.trace) Printer.trace(">>> DirectClip: run() threadID="+Thread.currentThread().getId());
             while (thread != null) {
-                if (!doIO) {
-                    synchronized(lock) {
+                // doIO is volatile, but we could check it, then get
+                // pre-empted while another thread changes doIO and notifies,
+                // before we wait (so we sleep in wait forever).
+                synchronized(lock) {
+                    if (!doIO) {
                         try {
                             lock.wait();
                         } catch(InterruptedException ie) {}
diff --git a/src/share/classes/com/sun/script/javascript/RhinoScriptEngine.java b/src/share/classes/com/sun/script/javascript/RhinoScriptEngine.java
index d370673..4c21fdb 100644
--- a/src/share/classes/com/sun/script/javascript/RhinoScriptEngine.java
+++ b/src/share/classes/com/sun/script/javascript/RhinoScriptEngine.java
@@ -61,26 +61,43 @@
     private ScriptEngineFactory factory;
     private InterfaceImplementor implementor;
 
+    private static final int languageVersion = getLanguageVersion();
+    private static final int optimizationLevel = getOptimizationLevel();
     static {
         ContextFactory.initGlobal(new ContextFactory() {
             protected Context makeContext() {
                 Context cx = super.makeContext();
+                cx.setLanguageVersion(languageVersion);
+                cx.setOptimizationLevel(optimizationLevel);
                 cx.setClassShutter(RhinoClassShutter.getInstance());
                 cx.setWrapFactory(RhinoWrapFactory.getInstance());
                 return cx;
             }
-
-            public boolean hasFeature(Context cx, int feature) {
-                // we do not support E4X (ECMAScript for XML)!
-                if (feature == Context.FEATURE_E4X) {
-                    return false;
-                } else {
-                    return super.hasFeature(cx, feature);
-                }
-            }
         });
     }
 
+    private static final String RHINO_JS_VERSION = "rhino.js.version";
+    private static int getLanguageVersion() {
+        int version;
+        String tmp = java.security.AccessController.doPrivileged(
+            new sun.security.action.GetPropertyAction(RHINO_JS_VERSION));
+        if (tmp != null) {
+            version = Integer.parseInt((String)tmp);
+        } else {
+            version = Context.VERSION_1_8;
+        }
+        return version;
+    }
+
+    private static final String RHINO_OPT_LEVEL = "rhino.opt.level";
+    private static int getOptimizationLevel() {
+        int optLevel = -1;
+        // disable optimizer under security manager, for now.
+        if (System.getSecurityManager() == null) {
+            optLevel = Integer.getInteger(RHINO_OPT_LEVEL, -1);
+        }
+        return optLevel;
+    }
 
     /**
      * Creates a new instance of RhinoScriptEngine
@@ -333,6 +350,7 @@
         return result instanceof Undefined ? null : result;
     }
 
+    /*
     public static void main(String[] args) throws Exception {
         if (args.length == 0) {
             System.out.println("No file specified");
@@ -347,4 +365,5 @@
         engine.eval(r);
         System.out.println(engine.get("x"));
     }
+    */
 }
diff --git a/src/share/classes/com/sun/script/javascript/RhinoScriptEngineFactory.java b/src/share/classes/com/sun/script/javascript/RhinoScriptEngineFactory.java
index 15937c3..3936a1a 100644
--- a/src/share/classes/com/sun/script/javascript/RhinoScriptEngineFactory.java
+++ b/src/share/classes/com/sun/script/javascript/RhinoScriptEngineFactory.java
@@ -58,11 +58,11 @@
         } else if (key.equals(ScriptEngine.ENGINE)) {
             return "Mozilla Rhino";
         } else if (key.equals(ScriptEngine.ENGINE_VERSION)) {
-            return "1.6 release 2";
+            return "1.7 release 3 PRERELEASE";
         } else if (key.equals(ScriptEngine.LANGUAGE)) {
             return "ECMAScript";
         } else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) {
-            return "1.6";
+            return "1.8";
         } else if (key.equals("THREADING")) {
             return "MULTITHREADED";
         } else {
@@ -128,10 +128,12 @@
         return ret;
     }
 
+    /*
     public static void main(String[] args) {
         RhinoScriptEngineFactory fact = new RhinoScriptEngineFactory();
         System.out.println(fact.getParameter(ScriptEngine.ENGINE_VERSION));
     }
+    */
 
     private static List<String> names;
     private static List<String> mimeTypes;
diff --git a/src/share/classes/com/sun/script/javascript/RhinoTopLevel.java b/src/share/classes/com/sun/script/javascript/RhinoTopLevel.java
index 44e5f95..a6b435a 100644
--- a/src/share/classes/com/sun/script/javascript/RhinoTopLevel.java
+++ b/src/share/classes/com/sun/script/javascript/RhinoTopLevel.java
@@ -37,15 +37,6 @@
  * @since 1.6
  */
 public final class RhinoTopLevel extends ImporterTopLevel {
-
-    // variables defined always to help Java access from JavaScript
-    private static final String builtinVariables =
-                "var com = Packages.com;                   \n" +
-                "var edu = Packages.edu;                   \n" +
-                "var javax = Packages.javax;               \n" +
-                "var net = Packages.net;                   \n" +
-                "var org = Packages.org;                   \n";
-
     RhinoTopLevel(Context cx, RhinoScriptEngine engine) {
         super(cx);
         this.engine = engine;
@@ -67,9 +58,6 @@
         String names[] = { "bindings", "scope", "sync"  };
         defineFunctionProperties(names, RhinoTopLevel.class,
                 ScriptableObject.DONTENUM);
-
-        // define built-in variables
-        cx.evaluateString(this, builtinVariables, "<builtin>", 1, null);
     }
 
     /**
diff --git a/src/share/classes/com/sun/tools/script/shell/init.js b/src/share/classes/com/sun/tools/script/shell/init.js
index 6abaf37..9b31ea4 100644
--- a/src/share/classes/com/sun/tools/script/shell/init.js
+++ b/src/share/classes/com/sun/tools/script/shell/init.js
@@ -311,9 +311,9 @@
 	try {
 		engine.eval(reader);
 	} finally {
-		engine.put(engine.FILENAME, oldFilename);	
+		engine.put(engine.FILENAME, oldFilename);
+	        streamClose(stream);
 	}
-	streamClose(stream);
 }
 
 // file system utilities
diff --git a/src/share/classes/java/awt/SplashScreen.java b/src/share/classes/java/awt/SplashScreen.java
index e236f07..867ecb3 100644
--- a/src/share/classes/java/awt/SplashScreen.java
+++ b/src/share/classes/java/awt/SplashScreen.java
@@ -33,27 +33,17 @@
 import sun.awt.image.SunWritableRaster;
 
 /**
- * The splash screen can be created at application startup, before the
+ * The splash screen can be displayed at application startup, before the
  * Java Virtual Machine (JVM) starts. The splash screen is displayed as an
- * undecorated window containing an image. You can use GIF, JPEG, and PNG files
- * for the image. Animation (for GIF) and transparency (for GIF, PNG) are
- * supported. The window is positioned at the center of the screen (the
- * position on multi-monitor systems is not specified - it is platform and
- * implementation dependent).
- * The window is closed automatically as soon as the first window is displayed by
- * Swing/AWT (may be also closed manually using the Java API, see below).
+ * undecorated window containing an image. You can use GIF, JPEG, or PNG files
+ * for the image. Animation is supported for the GIF format, while transparency
+ * is supported both for GIF and PNG.  The window is positioned at the center
+ * of the screen. The position on multi-monitor systems is not specified. It is
+ * platform and implementation dependent.  The splash screen window is closed
+ * automatically as soon as the first window is displayed by Swing/AWT (may be
+ * also closed manually using the Java API, see below).
  * <P>
- * There are two ways to show the native splash screen:
- * <P>
- * <UL>
- * <LI>If your application is run from the command line or from a shortcut,
- * use the "-splash:" Java application  launcher option to show a splash screen.
- * <BR>
- * For example:
- * <PRE>
- * java -splash:filename.gif Test
- * </PRE>
- * <LI>If your application is packaged in a jar file, you can use the
+ * If your application is packaged in a jar file, you can use the
  * "SplashScreen-Image" option in a manifest file to show a splash screen.
  * Place the image in the jar archive and specify the path in the option.
  * The path should not have a leading slash.
@@ -64,18 +54,39 @@
  * Main-Class: Test
  * SplashScreen-Image: filename.gif
  * </PRE>
+ * <P>
+ * If the Java implementation provides the command-line interface and you run
+ * your application by using the command line or a shortcut, use the Java
+ * application launcher option to show a splash screen. The Oracle reference
+ * implementation allows you to specify the splash screen image location with
+ * the {@code -splash:} option.
+ * <BR>
+ * For example:
+ * <PRE>
+ * java -splash:filename.gif Test
+ * </PRE>
  * The command line interface has higher precedence over the manifest
  * setting.
- * </UL>
+ * <p>
+ * The splash screen will be displayed as faithfully as possible to present the
+ * whole splash screen image given the limitations of the target platform and
+ * display.
+ * <p>
+ * It is implied that the specified image is presented on the screen "as is",
+ * i.e. preserving the exact color values as specified in the image file. Under
+ * certain circumstances, though, the presented image may differ, e.g. when
+ * applying color dithering to present a 32 bits per pixel (bpp) image on a 16
+ * or 8 bpp screen. The native platform display configuration may also affect
+ * the colors of the displayed image (e.g.  color profiles, etc.)
  * <p>
  * The {@code SplashScreen} class provides the API for controlling the splash
  * screen. This class may be used to close the splash screen, change the splash
- * screen image, get the image position/size and paint in the splash screen. It
- * cannot be used to create the splash screen; you should use the command line or manifest
- * file option for that.
+ * screen image, get the splash screen native window position/size, and paint
+ * in the splash screen. It cannot be used to create the splash screen. You
+ * should use the options provided by the Java implementation for that.
  * <p>
  * This class cannot be instantiated. Only a single instance of this class
- * can exist, and it may be obtained using the {@link #getSplashScreen()}
+ * can exist, and it may be obtained by using the {@link #getSplashScreen()}
  * static method. In case the splash screen has not been created at
  * application startup via the command line or manifest file option,
  * the <code>getSplashScreen</code> method returns <code>null</code>.
@@ -91,7 +102,7 @@
 
     /**
      * Returns the {@code SplashScreen} object used for
-     * Java startup splash screen control.
+     * Java startup splash screen control on systems that support display.
      *
      * @throws UnsupportedOperationException if the splash screen feature is not
      *         supported by the current toolkit
@@ -219,6 +230,9 @@
      * <p>
      * You cannot control the size or position of the splash screen.
      * The splash screen size is adjusted automatically when the image changes.
+     * <p>
+     * The image may contain transparent areas, and thus the reported bounds may
+     * be larger than the visible splash screen image on the screen.
      *
      * @return a {@code Rectangle} containing the splash screen bounds
      * @throws IllegalStateException if the splash screen has already been closed
@@ -237,6 +251,9 @@
      * <p>
      * You cannot control the size or position of the splash screen.
      * The splash screen size is adjusted automatically when the image changes.
+     * <p>
+     * The image may contain transparent areas, and thus the reported size may
+     * be larger than the visible splash screen image on the screen.
      *
      * @return a {@link Dimension} object indicating the splash screen size
      * @throws IllegalStateException if the splash screen has already been closed
@@ -254,6 +271,10 @@
      * screen window. You should call {@code update()} on the
      * <code>SplashScreen</code> when you want the splash screen to be
      * updated immediately.
+     * <p>
+     * The pixel (0, 0) in the coordinate space of the graphics context
+     * corresponds to the origin of the splash screen native window bounds (see
+     * {@link #getBounds()}).
      *
      * @return graphics context for the splash screen overlay surface
      * @throws IllegalStateException if the splash screen has already been closed
@@ -334,6 +355,11 @@
      * Determines whether the splash screen is visible. The splash screen may
      * be hidden using {@link #close()}, it is also hidden automatically when
      * the first AWT/Swing window is made visible.
+     * <p>
+     * Note that the native platform may delay presenting the splash screen
+     * native window on the screen. The return value of {@code true} for this
+     * method only guarantees that the conditions to hide the splash screen
+     * window have not occurred yet.
      *
      * @return true if the splash screen is visible (has not been closed yet),
      *         false otherwise
diff --git a/src/share/classes/java/awt/font/NumericShaper.java b/src/share/classes/java/awt/font/NumericShaper.java
index 0c57c29..c8100bf 100644
--- a/src/share/classes/java/awt/font/NumericShaper.java
+++ b/src/share/classes/java/awt/font/NumericShaper.java
@@ -58,20 +58,20 @@
  * It is also possible to perform numeric shaping explicitly using instances
  * of <code>NumericShaper</code>, as this code snippet demonstrates:<br>
  * <blockquote><pre>
- *   char[] text = ...;
- *   // shape all EUROPEAN digits (except zero) to ARABIC digits
- *   NumericShaper shaper = NumericShaper.getShaper(NumericShaper.ARABIC);
- *   shaper.shape(text, start, count);
+ * char[] text = ...;
+ * // shape all EUROPEAN digits (except zero) to ARABIC digits
+ * NumericShaper shaper = NumericShaper.getShaper(NumericShaper.ARABIC);
+ * shaper.shape(text, start, count);
  *
- *   // shape European digits to ARABIC digits if preceding text is Arabic, or
- *   // shape European digits to TAMIL digits if preceding text is Tamil, or
- *   // leave European digits alone if there is no preceding text, or
- *   // preceding text is neither Arabic nor Tamil
- *   NumericShaper shaper =
- *      NumericShaper.getContextualShaper(NumericShaper.ARABIC |
- *                                              NumericShaper.TAMIL,
- *                                              NumericShaper.EUROPEAN);
- *   shaper.shape(text, start, count);
+ * // shape European digits to ARABIC digits if preceding text is Arabic, or
+ * // shape European digits to TAMIL digits if preceding text is Tamil, or
+ * // leave European digits alone if there is no preceding text, or
+ * // preceding text is neither Arabic nor Tamil
+ * NumericShaper shaper =
+ *     NumericShaper.getContextualShaper(NumericShaper.ARABIC |
+ *                                         NumericShaper.TAMIL,
+ *                                       NumericShaper.EUROPEAN);
+ * shaper.shape(text, start, count);
  * </pre></blockquote>
  *
  * <p><b>Bit mask- and enum-based Unicode ranges</b></p>
@@ -99,6 +99,37 @@
  * values are specified, such as {@code NumericShaper.Range.BALINESE},
  * those ranges are ignored.
  *
+ * <p><b>Decimal Digits Precedence</b></p>
+ *
+ * <p>A Unicode range may have more than one set of decimal digits. If
+ * multiple decimal digits sets are specified for the same Unicode
+ * range, one of the sets will take precedence as follows.
+ *
+ * <table border=1 cellspacing=3 cellpadding=0 summary="NumericShaper constants precedence.">
+ *    <tr>
+ *       <th class="TableHeadingColor">Unicode Range</th>
+ *       <th class="TableHeadingColor"><code>NumericShaper</code> Constants</th>
+ *       <th class="TableHeadingColor">Precedence</th>
+ *    </tr>
+ *    <tr>
+ *       <td rowspan="2">Arabic</td>
+ *       <td>{@link NumericShaper#ARABIC NumericShaper.ARABIC}<br>
+ *           {@link NumericShaper#EASTERN_ARABIC NumericShaper.EASTERN_ARABIC}</td>
+ *       <td>{@link NumericShaper#EASTERN_ARABIC NumericShaper.EASTERN_ARABIC}</td>
+ *    </tr>
+ *    <tr>
+ *       <td>{@link NumericShaper.Range#ARABIC}<br>
+ *           {@link NumericShaper.Range#EASTERN_ARABIC}</td>
+ *       <td>{@link NumericShaper.Range#EASTERN_ARABIC}</td>
+ *    </tr>
+ *    <tr>
+ *       <td>Tai Tham</td>
+ *       <td>{@link NumericShaper.Range#TAI_THAM_HORA}<br>
+ *           {@link NumericShaper.Range#TAI_THAM_THAM}</td>
+ *       <td>{@link NumericShaper.Range#TAI_THAM_THAM}</td>
+ *    </tr>
+ * </table>
+ *
  * @since 1.4
  */
 
diff --git a/src/share/classes/java/io/DeleteOnExitHook.java b/src/share/classes/java/io/DeleteOnExitHook.java
index 8ad072d..2ce5c8e 100644
--- a/src/share/classes/java/io/DeleteOnExitHook.java
+++ b/src/share/classes/java/io/DeleteOnExitHook.java
@@ -34,7 +34,7 @@
  */
 
 class DeleteOnExitHook {
-    private static LinkedHashSet<String> files = new LinkedHashSet<String>();
+    private static LinkedHashSet<String> files = new LinkedHashSet<>();
     static {
         // DeleteOnExitHook must be the last shutdown hook to be invoked.
         // Application shutdown hooks may add the first file to the
@@ -71,7 +71,7 @@
             files = null;
         }
 
-        ArrayList<String> toBeDeleted = new ArrayList<String>(theFiles);
+        ArrayList<String> toBeDeleted = new ArrayList<>(theFiles);
 
         // reverse the list to maintain previous jdk deletion order.
         // Last in first deleted.
diff --git a/src/share/classes/java/io/File.java b/src/share/classes/java/io/File.java
index 58a4e9c..1ff3e93 100644
--- a/src/share/classes/java/io/File.java
+++ b/src/share/classes/java/io/File.java
@@ -1067,7 +1067,7 @@
         if ((names == null) || (filter == null)) {
             return names;
         }
-        List<String> v = new ArrayList<String>();
+        List<String> v = new ArrayList<>();
         for (int i = 0 ; i < names.length ; i++) {
             if (filter.accept(this, names[i])) {
                 v.add(names[i]);
@@ -1158,7 +1158,7 @@
     public File[] listFiles(FilenameFilter filter) {
         String ss[] = list();
         if (ss == null) return null;
-        ArrayList<File> files = new ArrayList<File>();
+        ArrayList<File> files = new ArrayList<>();
         for (String s : ss)
             if ((filter == null) || filter.accept(this, s))
                 files.add(new File(s, this));
@@ -1195,7 +1195,7 @@
     public File[] listFiles(FileFilter filter) {
         String ss[] = list();
         if (ss == null) return null;
-        ArrayList<File> files = new ArrayList<File>();
+        ArrayList<File> files = new ArrayList<>();
         for (String s : ss) {
             File f = new File(s, this);
             if ((filter == null) || filter.accept(f))
diff --git a/src/share/classes/java/io/FileInputStream.java b/src/share/classes/java/io/FileInputStream.java
index bcc43d9..23530c1 100644
--- a/src/share/classes/java/io/FileInputStream.java
+++ b/src/share/classes/java/io/FileInputStream.java
@@ -56,7 +56,7 @@
     private volatile boolean closed = false;
 
     private static final ThreadLocal<Boolean> runningFinalize =
-        new ThreadLocal<Boolean>();
+        new ThreadLocal<>();
 
     private static boolean isRunningFinalize() {
         Boolean val;
diff --git a/src/share/classes/java/io/FileOutputStream.java b/src/share/classes/java/io/FileOutputStream.java
index 2b9bb85..3fe3a59 100644
--- a/src/share/classes/java/io/FileOutputStream.java
+++ b/src/share/classes/java/io/FileOutputStream.java
@@ -69,7 +69,7 @@
     private final Object closeLock = new Object();
     private volatile boolean closed = false;
     private static final ThreadLocal<Boolean> runningFinalize =
-        new ThreadLocal<Boolean>();
+        new ThreadLocal<>();
 
     private static boolean isRunningFinalize() {
         Boolean val;
diff --git a/src/share/classes/java/io/FilePermission.java b/src/share/classes/java/io/FilePermission.java
index be847b1..06b4f3b 100644
--- a/src/share/classes/java/io/FilePermission.java
+++ b/src/share/classes/java/io/FilePermission.java
@@ -725,7 +725,7 @@
      */
 
     public FilePermissionCollection() {
-        perms = new ArrayList<Permission>();
+        perms = new ArrayList<>();
     }
 
     /**
@@ -830,7 +830,7 @@
         // Don't call out.defaultWriteObject()
 
         // Write out Vector
-        Vector<Permission> permissions = new Vector<Permission>(perms.size());
+        Vector<Permission> permissions = new Vector<>(perms.size());
         synchronized (this) {
             permissions.addAll(perms);
         }
@@ -853,7 +853,7 @@
 
         // Get the one we want
         Vector<Permission> permissions = (Vector<Permission>)gfields.get("permissions", null);
-        perms = new ArrayList<Permission>(permissions.size());
+        perms = new ArrayList<>(permissions.size());
         perms.addAll(permissions);
     }
 }
diff --git a/src/share/classes/java/io/ObjectInputStream.java b/src/share/classes/java/io/ObjectInputStream.java
index 3ec3cd4..26a764f 100644
--- a/src/share/classes/java/io/ObjectInputStream.java
+++ b/src/share/classes/java/io/ObjectInputStream.java
@@ -213,7 +213,7 @@
 
     /** table mapping primitive type names to corresponding class objects */
     private static final HashMap<String, Class<?>> primClasses
-        = new HashMap<String, Class<?>>(8, 1.0F);
+        = new HashMap<>(8, 1.0F);
     static {
         primClasses.put("boolean", boolean.class);
         primClasses.put("byte", byte.class);
@@ -229,11 +229,11 @@
     private static class Caches {
         /** cache of subclass security audit results */
         static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
-            new ConcurrentHashMap<WeakClassKey,Boolean>();
+            new ConcurrentHashMap<>();
 
         /** queue for WeakReferences to audited subclasses */
         static final ReferenceQueue<Class<?>> subclassAuditsQueue =
-            new ReferenceQueue<Class<?>>();
+            new ReferenceQueue<>();
     }
 
     /** filter stream for handling block data conversion */
diff --git a/src/share/classes/java/io/ObjectOutputStream.java b/src/share/classes/java/io/ObjectOutputStream.java
index 5b37e4d..76a08f3 100644
--- a/src/share/classes/java/io/ObjectOutputStream.java
+++ b/src/share/classes/java/io/ObjectOutputStream.java
@@ -165,11 +165,11 @@
     private static class Caches {
         /** cache of subclass security audit results */
         static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
-            new ConcurrentHashMap<WeakClassKey,Boolean>();
+            new ConcurrentHashMap<>();
 
         /** queue for WeakReferences to audited subclasses */
         static final ReferenceQueue<Class<?>> subclassAuditsQueue =
-            new ReferenceQueue<Class<?>>();
+            new ReferenceQueue<>();
     }
 
     /** filter stream for handling block data conversion */
@@ -2413,7 +2413,7 @@
         private final List<String> stack;
 
         DebugTraceInfoStack() {
-            stack = new ArrayList<String>();
+            stack = new ArrayList<>();
         }
 
         /**
diff --git a/src/share/classes/java/io/ObjectStreamClass.java b/src/share/classes/java/io/ObjectStreamClass.java
index b3842f9..2d3e205 100644
--- a/src/share/classes/java/io/ObjectStreamClass.java
+++ b/src/share/classes/java/io/ObjectStreamClass.java
@@ -84,18 +84,18 @@
     private static class Caches {
         /** cache mapping local classes -> descriptors */
         static final ConcurrentMap<WeakClassKey,Reference<?>> localDescs =
-            new ConcurrentHashMap<WeakClassKey,Reference<?>>();
+            new ConcurrentHashMap<>();
 
         /** cache mapping field group/local desc pairs -> field reflectors */
         static final ConcurrentMap<FieldReflectorKey,Reference<?>> reflectors =
-            new ConcurrentHashMap<FieldReflectorKey,Reference<?>>();
+            new ConcurrentHashMap<>();
 
         /** queue for WeakReferences to local classes */
         private static final ReferenceQueue<Class<?>> localDescsQueue =
-            new ReferenceQueue<Class<?>>();
+            new ReferenceQueue<>();
         /** queue for WeakReferences to field reflectors keys */
         private static final ReferenceQueue<Class<?>> reflectorsQueue =
-            new ReferenceQueue<Class<?>>();
+            new ReferenceQueue<>();
     }
 
     /** class associated with this descriptor (if any) */
@@ -290,7 +290,7 @@
         EntryFuture future = null;
         if (entry == null) {
             EntryFuture newEntry = new EntryFuture();
-            Reference<?> newRef = new SoftReference<EntryFuture>(newEntry);
+            Reference<?> newRef = new SoftReference<>(newEntry);
             do {
                 if (ref != null) {
                     Caches.localDescs.remove(key, ref);
@@ -329,7 +329,7 @@
                 entry = th;
             }
             if (future.set(entry)) {
-                Caches.localDescs.put(key, new SoftReference<Object>(entry));
+                Caches.localDescs.put(key, new SoftReference<>(entry));
             } else {
                 // nested lookup call already set future
                 entry = future.get();
@@ -1130,7 +1130,7 @@
     private ClassDataSlot[] getClassDataLayout0()
         throws InvalidClassException
     {
-        ArrayList<ClassDataSlot> slots = new ArrayList<ClassDataSlot>();
+        ArrayList<ClassDataSlot> slots = new ArrayList<>();
         Class<?> start = cl, end = cl;
 
         // locate closest non-serializable superclass
@@ -1566,7 +1566,7 @@
 
         ObjectStreamField[] boundFields =
             new ObjectStreamField[serialPersistentFields.length];
-        Set<String> fieldNames = new HashSet<String>(serialPersistentFields.length);
+        Set<String> fieldNames = new HashSet<>(serialPersistentFields.length);
 
         for (int i = 0; i < serialPersistentFields.length; i++) {
             ObjectStreamField spf = serialPersistentFields[i];
@@ -1604,7 +1604,7 @@
      */
     private static ObjectStreamField[] getDefaultSerialFields(Class<?> cl) {
         Field[] clFields = cl.getDeclaredFields();
-        ArrayList<ObjectStreamField> list = new ArrayList<ObjectStreamField>();
+        ArrayList<ObjectStreamField> list = new ArrayList<>();
         int mask = Modifier.STATIC | Modifier.TRANSIENT;
 
         for (int i = 0; i < clFields.length; i++) {
@@ -1855,8 +1855,8 @@
             writeKeys = new long[nfields];
             offsets = new int[nfields];
             typeCodes = new char[nfields];
-            ArrayList<Class<?>> typeList = new ArrayList<Class<?>>();
-            Set<Long> usedKeys = new HashSet<Long>();
+            ArrayList<Class<?>> typeList = new ArrayList<>();
+            Set<Long> usedKeys = new HashSet<>();
 
 
             for (int i = 0; i < nfields; i++) {
@@ -2092,7 +2092,7 @@
         EntryFuture future = null;
         if (entry == null) {
             EntryFuture newEntry = new EntryFuture();
-            Reference<?> newRef = new SoftReference<EntryFuture>(newEntry);
+            Reference<?> newRef = new SoftReference<>(newEntry);
             do {
                 if (ref != null) {
                     Caches.reflectors.remove(key, ref);
@@ -2118,7 +2118,7 @@
                 entry = th;
             }
             future.set(entry);
-            Caches.reflectors.put(key, new SoftReference<Object>(entry));
+            Caches.reflectors.put(key, new SoftReference<>(entry));
         }
 
         if (entry instanceof FieldReflector) {
diff --git a/src/share/classes/java/lang/ApplicationShutdownHooks.java b/src/share/classes/java/lang/ApplicationShutdownHooks.java
index 665a351..34b2846 100644
--- a/src/share/classes/java/lang/ApplicationShutdownHooks.java
+++ b/src/share/classes/java/lang/ApplicationShutdownHooks.java
@@ -47,7 +47,7 @@
                     }
                 }
             );
-            hooks = new IdentityHashMap<Thread, Thread>();
+            hooks = new IdentityHashMap<>();
         } catch (IllegalStateException e) {
             // application shutdown hooks cannot be added if
             // shutdown is in progress.
diff --git a/src/share/classes/java/lang/Character.java b/src/share/classes/java/lang/Character.java
index f8be10e..0289d54 100644
--- a/src/share/classes/java/lang/Character.java
+++ b/src/share/classes/java/lang/Character.java
@@ -648,8 +648,7 @@
      */
     public static final class UnicodeBlock extends Subset {
 
-        private static Map<String, UnicodeBlock> map
-            = new HashMap<String, UnicodeBlock>(256);
+        private static Map<String, UnicodeBlock> map = new HashMap<>(256);
 
         /**
          * Creates a UnicodeBlock with the given identifier name.
@@ -4178,7 +4177,7 @@
 
         private static HashMap<String, Character.UnicodeScript> aliases;
         static {
-            aliases = new HashMap<String, UnicodeScript>(128);
+            aliases = new HashMap<>(128);
             aliases.put("ARAB", ARABIC);
             aliases.put("ARMI", IMPERIAL_ARAMAIC);
             aliases.put("ARMN", ARMENIAN);
diff --git a/src/share/classes/java/lang/CharacterName.java b/src/share/classes/java/lang/CharacterName.java
index cac053b..fa0b2d6 100644
--- a/src/share/classes/java/lang/CharacterName.java
+++ b/src/share/classes/java/lang/CharacterName.java
@@ -81,7 +81,7 @@
             } while (cpOff < cpEnd);
             strPool = new byte[total - cpEnd];
             dis.readFully(strPool);
-            refStrPool = new SoftReference<byte[]>(strPool);
+            refStrPool = new SoftReference<>(strPool);
         } catch (Exception x) {
             throw new InternalError(x.getMessage());
         } finally {
diff --git a/src/share/classes/java/lang/Class.java b/src/share/classes/java/lang/Class.java
index c3a662f..db76523 100644
--- a/src/share/classes/java/lang/Class.java
+++ b/src/share/classes/java/lang/Class.java
@@ -1306,7 +1306,7 @@
         return java.security.AccessController.doPrivileged(
             new java.security.PrivilegedAction<Class<?>[]>() {
                 public Class[] run() {
-                    List<Class<?>> list = new ArrayList<Class<?>>();
+                    List<Class<?>> list = new ArrayList<>();
                     Class<?> currentClass = Class.this;
                     while (currentClass != null) {
                         Class<?>[] members = currentClass.getDeclaredClasses();
@@ -2306,9 +2306,9 @@
         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
         if (useCaches) {
             if (publicOnly) {
-                declaredPublicFields = new SoftReference<Field[]>(res);
+                declaredPublicFields = new SoftReference<>(res);
             } else {
-                declaredFields = new SoftReference<Field[]>(res);
+                declaredFields = new SoftReference<>(res);
             }
         }
         return res;
@@ -2330,9 +2330,9 @@
 
         // No cached value available; compute value recursively.
         // Traverse in correct order for getField().
-        List<Field> fields = new ArrayList<Field>();
+        List<Field> fields = new ArrayList<>();
         if (traversedInterfaces == null) {
-            traversedInterfaces = new HashSet<Class<?>>();
+            traversedInterfaces = new HashSet<>();
         }
 
         // Local fields
@@ -2358,7 +2358,7 @@
         res = new Field[fields.size()];
         fields.toArray(res);
         if (useCaches) {
-            publicFields = new SoftReference<Field[]>(res);
+            publicFields = new SoftReference<>(res);
         }
         return res;
     }
@@ -2403,9 +2403,9 @@
         }
         if (useCaches) {
             if (publicOnly) {
-                publicConstructors = new SoftReference<Constructor<T>[]>(res);
+                publicConstructors = new SoftReference<>(res);
             } else {
-                declaredConstructors = new SoftReference<Constructor<T>[]>(res);
+                declaredConstructors = new SoftReference<>(res);
             }
         }
         return res;
@@ -2440,9 +2440,9 @@
         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
         if (useCaches) {
             if (publicOnly) {
-                declaredPublicMethods = new SoftReference<Method[]>(res);
+                declaredPublicMethods = new SoftReference<>(res);
             } else {
-                declaredMethods = new SoftReference<Method[]>(res);
+                declaredMethods = new SoftReference<>(res);
             }
         }
         return res;
@@ -2598,7 +2598,7 @@
         methods.compactAndTrim();
         res = methods.getArray();
         if (useCaches) {
-            publicMethods = new SoftReference<Method[]>(res);
+            publicMethods = new SoftReference<>(res);
         }
         return res;
     }
@@ -2977,7 +2977,7 @@
             if (universe == null)
                 throw new IllegalArgumentException(
                     getName() + " is not an enum type");
-            Map<String, T> m = new HashMap<String, T>(2 * universe.length);
+            Map<String, T> m = new HashMap<>(2 * universe.length);
             for (T constant : universe)
                 m.put(((Enum<?>)constant).name(), constant);
             enumConstantDirectory = m;
@@ -3090,7 +3090,7 @@
         if (superClass == null) {
             annotations = declaredAnnotations;
         } else {
-            annotations = new HashMap<Class<? extends Annotation>, Annotation>();
+            annotations = new HashMap<>();
             superClass.initAnnotationsIfNecessary();
             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) {
                 Class<? extends Annotation> annotationClass = e.getKey();
diff --git a/src/share/classes/java/lang/ClassLoader.java b/src/share/classes/java/lang/ClassLoader.java
index d0cfb07..0e3cc28 100644
--- a/src/share/classes/java/lang/ClassLoader.java
+++ b/src/share/classes/java/lang/ClassLoader.java
@@ -247,7 +247,7 @@
 
     // The classes loaded by this class loader. The only purpose of this table
     // is to keep the classes from being GC'ed until the loader is GC'ed.
-    private final Vector<Class<?>> classes = new Vector<Class<?>>();
+    private final Vector<Class<?>> classes = new Vector<>();
 
     // The "default" domain. Set as the default ProtectionDomain on newly
     // created classes.
@@ -266,8 +266,7 @@
     // The packages defined in this class loader.  Each package name is mapped
     // to its corresponding Package object.
     // @GuardedBy("itself")
-    private final HashMap<String, Package> packages =
-        new HashMap<String, Package>();
+    private final HashMap<String, Package> packages = new HashMap<>();
 
     private static Void checkCreateClassLoader() {
         SecurityManager security = System.getSecurityManager();
@@ -280,16 +279,16 @@
     private ClassLoader(Void unused, ClassLoader parent) {
         this.parent = parent;
         if (ParallelLoaders.isRegistered(this.getClass())) {
-            parallelLockMap = new ConcurrentHashMap<String, Object>();
-            package2certs = new ConcurrentHashMap<String, Certificate[]>();
+            parallelLockMap = new ConcurrentHashMap<>();
+            package2certs = new ConcurrentHashMap<>();
             domains =
                 Collections.synchronizedSet(new HashSet<ProtectionDomain>());
             assertionLock = new Object();
         } else {
             // no finer-grained lock; lock on the classloader instance
             parallelLockMap = null;
-            package2certs = new Hashtable<String, Certificate[]>();
-            domains = new HashSet<ProtectionDomain>();
+            package2certs = new Hashtable<>();
+            domains = new HashSet<>();
             assertionLock = this;
         }
     }
@@ -1182,7 +1181,7 @@
         }
         tmp[1] = findResources(name);
 
-        return new CompoundEnumeration<URL>(tmp);
+        return new CompoundEnumeration<>(tmp);
     }
 
     /**
@@ -1657,7 +1656,7 @@
     protected Package[] getPackages() {
         Map<String, Package> map;
         synchronized (packages) {
-            map = new HashMap<String, Package>(packages);
+            map = new HashMap<>(packages);
         }
         Package[] pkgs;
         if (parent != null) {
@@ -1764,20 +1763,17 @@
     }
 
     // All native library names we've loaded.
-    private static Vector<String> loadedLibraryNames
-        = new Vector<String>();
+    private static Vector<String> loadedLibraryNames = new Vector<>();
 
     // Native libraries belonging to system classes.
     private static Vector<NativeLibrary> systemNativeLibraries
-        = new Vector<NativeLibrary>();
+        = new Vector<>();
 
     // Native libraries associated with the class loader.
-    private Vector<NativeLibrary> nativeLibraries
-        = new Vector<NativeLibrary>();
+    private Vector<NativeLibrary> nativeLibraries = new Vector<>();
 
     // native libraries being loaded/unloaded.
-    private static Stack<NativeLibrary> nativeLibraryContext
-        = new Stack<NativeLibrary>();
+    private static Stack<NativeLibrary> nativeLibraryContext = new Stack<>();
 
     // The paths searched for libraries
     private static String usr_paths[];
@@ -2101,8 +2097,8 @@
          * them to empty maps, effectively ignoring any present settings.
          */
         synchronized (assertionLock) {
-            classAssertionStatus = new HashMap<String, Boolean>();
-            packageAssertionStatus = new HashMap<String, Boolean>();
+            classAssertionStatus = new HashMap<>();
+            packageAssertionStatus = new HashMap<>();
             defaultAssertionStatus = false;
         }
     }
@@ -2164,8 +2160,8 @@
     private void initializeJavaAssertionMaps() {
         // assert Thread.holdsLock(assertionLock);
 
-        classAssertionStatus = new HashMap<String, Boolean>();
-        packageAssertionStatus = new HashMap<String, Boolean>();
+        classAssertionStatus = new HashMap<>();
+        packageAssertionStatus = new HashMap<>();
         AssertionStatusDirectives directives = retrieveDirectives();
 
         for(int i = 0; i < directives.classes.length; i++)
diff --git a/src/share/classes/java/lang/Package.java b/src/share/classes/java/lang/Package.java
index 92cadeb..99db694 100644
--- a/src/share/classes/java/lang/Package.java
+++ b/src/share/classes/java/lang/Package.java
@@ -588,16 +588,13 @@
     }
 
     // The map of loaded system packages
-    private static Map<String, Package> pkgs
-        = new HashMap<String, Package>(31);
+    private static Map<String, Package> pkgs = new HashMap<>(31);
 
     // Maps each directory or zip file name to its corresponding url
-    private static Map<String, URL> urls
-        = new HashMap<String, URL>(10);
+    private static Map<String, URL> urls = new HashMap<>(10);
 
     // Maps each code source url for a jar file to its manifest
-    private static Map<String, Manifest> mans
-        = new HashMap<String, Manifest>(10);
+    private static Map<String, Manifest> mans = new HashMap<>(10);
 
     private static native String getSystemPackage0(String name);
     private static native String[] getSystemPackages0();
diff --git a/src/share/classes/java/lang/ProcessBuilder.java b/src/share/classes/java/lang/ProcessBuilder.java
index 78f5156..c580f50 100644
--- a/src/share/classes/java/lang/ProcessBuilder.java
+++ b/src/share/classes/java/lang/ProcessBuilder.java
@@ -214,7 +214,7 @@
      * @param command a string array containing the program and its arguments
      */
     public ProcessBuilder(String... command) {
-        this.command = new ArrayList<String>(command.length);
+        this.command = new ArrayList<>(command.length);
         for (String arg : command)
             this.command.add(arg);
     }
@@ -251,7 +251,7 @@
      * @return this process builder
      */
     public ProcessBuilder command(String... command) {
-        this.command = new ArrayList<String>(command.length);
+        this.command = new ArrayList<>(command.length);
         for (String arg : command)
             this.command.add(arg);
         return this;
diff --git a/src/share/classes/java/lang/String.java b/src/share/classes/java/lang/String.java
index 4ab0772..7cadf9e 100644
--- a/src/share/classes/java/lang/String.java
+++ b/src/share/classes/java/lang/String.java
@@ -2330,7 +2330,7 @@
             int off = 0;
             int next = 0;
             boolean limited = limit > 0;
-            ArrayList<String> list = new ArrayList<String>();
+            ArrayList<String> list = new ArrayList<>();
             while ((next = indexOf(ch, off)) != -1) {
                 if (!limited || list.size() < limit - 1) {
                     list.add(substring(off, next));
diff --git a/src/share/classes/java/lang/StringCoding.java b/src/share/classes/java/lang/StringCoding.java
index 0a85e27..4284947 100644
--- a/src/share/classes/java/lang/StringCoding.java
+++ b/src/share/classes/java/lang/StringCoding.java
@@ -53,9 +53,9 @@
 
     /** The cached coders for each thread */
     private final static ThreadLocal<SoftReference<StringDecoder>> decoder =
-        new ThreadLocal<SoftReference<StringDecoder>>();
+        new ThreadLocal<>();
     private final static ThreadLocal<SoftReference<StringEncoder>> encoder =
-        new ThreadLocal<SoftReference<StringEncoder>>();
+        new ThreadLocal<>();
 
     private static boolean warnUnsupportedCharset = true;
 
@@ -67,7 +67,7 @@
     }
 
     private static <T> void set(ThreadLocal<SoftReference<T>> tl, T ob) {
-        tl.set(new SoftReference<T>(ob));
+        tl.set(new SoftReference<>(ob));
     }
 
     // Trim the given byte array to the given length
diff --git a/src/share/classes/java/lang/Thread.java b/src/share/classes/java/lang/Thread.java
index 628224b..3e258e6 100644
--- a/src/share/classes/java/lang/Thread.java
+++ b/src/share/classes/java/lang/Thread.java
@@ -1642,8 +1642,7 @@
         // Get a snapshot of the list of all threads
         Thread[] threads = getThreads();
         StackTraceElement[][] traces = dumpThreads(threads);
-        Map<Thread, StackTraceElement[]> m
-            = new HashMap<Thread, StackTraceElement[]>(threads.length);
+        Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length);
         for (int i = 0; i < threads.length; i++) {
             StackTraceElement[] stackTrace = traces[i];
             if (stackTrace != null) {
@@ -1664,11 +1663,11 @@
     private static class Caches {
         /** cache of subclass security audit results */
         static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
-            new ConcurrentHashMap<WeakClassKey,Boolean>();
+            new ConcurrentHashMap<>();
 
         /** queue for WeakReferences to audited subclasses */
         static final ReferenceQueue<Class<?>> subclassAuditsQueue =
-            new ReferenceQueue<Class<?>>();
+            new ReferenceQueue<>();
     }
 
     /**
diff --git a/src/share/classes/java/lang/Throwable.java b/src/share/classes/java/lang/Throwable.java
index 16070c8..22400ba 100644
--- a/src/share/classes/java/lang/Throwable.java
+++ b/src/share/classes/java/lang/Throwable.java
@@ -828,7 +828,7 @@
                 // Use the sentinel for a zero-length list
                 suppressed = SUPPRESSED_SENTINEL;
             } else { // Copy Throwables to new list
-                suppressed = new ArrayList<Throwable>(1);
+                suppressed = new ArrayList<>(1);
                 for (Throwable t : suppressedExceptions) {
                     // Enforce constraints on suppressed exceptions in
                     // case of corrupt or malicious stream.
@@ -911,7 +911,7 @@
                 return;
 
             if (suppressedExceptions == SUPPRESSED_SENTINEL)
-                suppressedExceptions = new ArrayList<Throwable>(1);
+                suppressedExceptions = new ArrayList<>(1);
 
             assert suppressedExceptions != SUPPRESSED_SENTINEL;
 
diff --git a/src/share/classes/java/lang/management/ManagementFactory.java b/src/share/classes/java/lang/management/ManagementFactory.java
index 876ff87..bfe9d23 100644
--- a/src/share/classes/java/lang/management/ManagementFactory.java
+++ b/src/share/classes/java/lang/management/ManagementFactory.java
@@ -794,7 +794,7 @@
      */
     public static List<Class<? extends PlatformManagedObject>> getAllPlatformMXBeanInterfaces() {
         List<Class<? extends PlatformManagedObject>> result =
-            new ArrayList<Class<? extends PlatformManagedObject>>();
+            new ArrayList<>();
         for (PlatformComponent component: PlatformComponent.values()) {
             result.add(component.getMXBeanInterface());
         }
diff --git a/src/share/classes/java/lang/management/PlatformComponent.java b/src/share/classes/java/lang/management/PlatformComponent.java
index 26f30a2..4b8056e 100644
--- a/src/share/classes/java/lang/management/PlatformComponent.java
+++ b/src/share/classes/java/lang/management/PlatformComponent.java
@@ -267,7 +267,7 @@
             List<T> getGcMXBeanList(Class<T> gcMXBeanIntf) {
         List<GarbageCollectorMXBean> list =
             ManagementFactoryHelper.getGarbageCollectorMXBeans();
-        List<T> result = new ArrayList<T>(list.size());
+        List<T> result = new ArrayList<>(list.size());
         for (GarbageCollectorMXBean m : list) {
             if (gcMXBeanIntf.isInstance(m)) {
                 result.add(gcMXBeanIntf.cast(m));
@@ -330,7 +330,7 @@
     }
 
     private static Set<String> keyProperties(String... keyNames) {
-        Set<String> set = new HashSet<String>();
+        Set<String> set = new HashSet<>();
         set.add("type");
         for (String s : keyNames) {
             set.add(s);
@@ -364,7 +364,7 @@
         List<T> getMXBeans(MBeanServerConnection mbs, Class<T> mxbeanInterface)
         throws java.io.IOException
     {
-        List<T> result = new ArrayList<T>();
+        List<T> result = new ArrayList<>();
         for (ObjectName on : getObjectNames(mbs)) {
             result.add(ManagementFactory.
                 newPlatformMXBeanProxy(mbs,
diff --git a/src/share/classes/java/lang/reflect/Constructor.java b/src/share/classes/java/lang/reflect/Constructor.java
index 682cf70..601eafe 100644
--- a/src/share/classes/java/lang/reflect/Constructor.java
+++ b/src/share/classes/java/lang/reflect/Constructor.java
@@ -144,7 +144,7 @@
         // which implicitly requires that new java.lang.reflect
         // objects be fabricated for each reflective call on Class
         // objects.)
-        Constructor<T> res = new Constructor<T>(clazz,
+        Constructor<T> res = new Constructor<>(clazz,
                                                 parameterTypes,
                                                 exceptionTypes, modifiers, slot,
                                                 signature,
diff --git a/src/share/classes/java/lang/reflect/Proxy.java b/src/share/classes/java/lang/reflect/Proxy.java
index 7ed8e35..102085d 100644
--- a/src/share/classes/java/lang/reflect/Proxy.java
+++ b/src/share/classes/java/lang/reflect/Proxy.java
@@ -232,7 +232,7 @@
 
     /** maps a class loader to the proxy class cache for that loader */
     private static Map<ClassLoader, Map<List<String>, Object>> loaderToCache
-        = new WeakHashMap<ClassLoader, Map<List<String>, Object>>();
+        = new WeakHashMap<>();
 
     /** marks that a particular proxy class is currently being generated */
     private static Object pendingGenerationMarker = new Object();
@@ -356,7 +356,7 @@
         String[] interfaceNames = new String[interfaces.length];
 
         // for detecting duplicates
-        Set<Class<?>> interfaceSet = new HashSet<Class<?>>();
+        Set<Class<?>> interfaceSet = new HashSet<>();
 
         for (int i = 0; i < interfaces.length; i++) {
             /*
@@ -413,7 +413,7 @@
         synchronized (loaderToCache) {
             cache = loaderToCache.get(loader);
             if (cache == null) {
-                cache = new HashMap<List<String>, Object>();
+                cache = new HashMap<>();
                 loaderToCache.put(loader, cache);
             }
             /*
diff --git a/src/share/classes/java/lang/reflect/ReflectAccess.java b/src/share/classes/java/lang/reflect/ReflectAccess.java
index 85689cc..56759de 100644
--- a/src/share/classes/java/lang/reflect/ReflectAccess.java
+++ b/src/share/classes/java/lang/reflect/ReflectAccess.java
@@ -84,7 +84,7 @@
                                              byte[] annotations,
                                              byte[] parameterAnnotations)
     {
-        return new Constructor<T>(declaringClass,
+        return new Constructor<>(declaringClass,
                                   parameterTypes,
                                   checkedExceptions,
                                   modifiers,
diff --git a/src/share/classes/java/sql/DriverManager.java b/src/share/classes/java/sql/DriverManager.java
index 1da9fce..1527387 100644
--- a/src/share/classes/java/sql/DriverManager.java
+++ b/src/share/classes/java/sql/DriverManager.java
@@ -364,7 +364,7 @@
      * @return the list of JDBC Drivers loaded by the caller's class loader
      */
     public static java.util.Enumeration<Driver> getDrivers() {
-        java.util.Vector<Driver> result = new java.util.Vector<Driver>();
+        java.util.Vector<Driver> result = new java.util.Vector<>();
         java.util.Vector drivers = null;
 
         if (!initialized) {
diff --git a/src/share/classes/java/sql/Statement.java b/src/share/classes/java/sql/Statement.java
index d7f5bcf..da7285e 100644
--- a/src/share/classes/java/sql/Statement.java
+++ b/src/share/classes/java/sql/Statement.java
@@ -577,7 +577,7 @@
      *
      * @see #addBatch
      * @see DatabaseMetaData#supportsBatchUpdates
-     * @since 1.3
+     * @since 1.2
      */
     int[] executeBatch() throws SQLException;
 
diff --git a/src/share/classes/java/text/MessageFormat.java b/src/share/classes/java/text/MessageFormat.java
index ed155e9..6590e76 100644
--- a/src/share/classes/java/text/MessageFormat.java
+++ b/src/share/classes/java/text/MessageFormat.java
@@ -93,73 +93,65 @@
  *         currency
  *         percent
  *         <i>SubformatPattern</i>
- *
- * <i>String:</i>
- *         <i>StringPart<sub>opt</sub></i>
- *         <i>String</i> <i>StringPart</i>
- *
- * <i>StringPart:</i>
- *         ''
- *         ' <i>QuotedString</i> '
- *         <i>UnquotedString</i>
- *
- * <i>SubformatPattern:</i>
- *         <i>SubformatPatternPart<sub>opt</sub></i>
- *         <i>SubformatPattern</i> <i>SubformatPatternPart</i>
- *
- * <i>SubFormatPatternPart:</i>
- *         ' <i>QuotedPattern</i> '
- *         <i>UnquotedPattern</i>
  * </pre></blockquote>
  *
- * <p>
- * Within a <i>String</i>, <code>"''"</code> represents a single
- * quote. A <i>QuotedString</i> can contain arbitrary characters
- * except single quotes; the surrounding single quotes are removed.
- * An <i>UnquotedString</i> can contain arbitrary characters
- * except single quotes and left curly brackets. Thus, a string that
- * should result in the formatted message "'{0}'" can be written as
- * <code>"'''{'0}''"</code> or <code>"'''{0}'''"</code>.
- * <p>
- * Within a <i>SubformatPattern</i>, different rules apply.
- * A <i>QuotedPattern</i> can contain arbitrary characters
- * except single quotes; but the surrounding single quotes are
- * <strong>not</strong> removed, so they may be interpreted by the
- * subformat. For example, <code>"{1,number,$'#',##}"</code> will
- * produce a number format with the pound-sign quoted, with a result
- * such as: "$#31,45".
- * An <i>UnquotedPattern</i> can contain arbitrary characters
- * except single quotes, but curly braces within it must be balanced.
- * For example, <code>"ab {0} de"</code> and <code>"ab '}' de"</code>
- * are valid subformat patterns, but <code>"ab {0'}' de"</code> and
- * <code>"ab } de"</code> are not.
+ * <p>Within a <i>String</i>, a pair of single quotes can be used to
+ * quote any arbitrary characters except single quotes. For example,
+ * pattern string <code>"'{0}'"</code> represents string
+ * <code>"{0}"</code>, not a <i>FormatElement</i>. A single quote itself
+ * must be represented by doubled single quotes {@code ''} throughout a
+ * <i>String</i>.  For example, pattern string <code>"'{''}'"</code> is
+ * interpreted as a sequence of <code>'{</code> (start of quoting and a
+ * left curly brace), <code>''</code> (a single quote), and
+ * <code>}'</code> (a right curly brace and end of quoting),
+ * <em>not</em> <code>'{'</code> and <code>'}'</code> (quoted left and
+ * right curly braces): representing string <code>"{'}"</code>,
+ * <em>not</em> <code>"{}"</code>.
+ *
+ * <p>A <i>SubformatPattern</i> is interpreted by its corresponding
+ * subformat, and subformat-dependent pattern rules apply. For example,
+ * pattern string <code>"{1,number,<u>$'#',##</u>}"</code>
+ * (<i>SubformatPattern</i> with underline) will produce a number format
+ * with the pound-sign quoted, with a result such as: {@code
+ * "$#31,45"}. Refer to each {@code Format} subclass documentation for
+ * details.
+ *
+ * <p>Any unmatched quote is treated as closed at the end of the given
+ * pattern. For example, pattern string {@code "'{0}"} is treated as
+ * pattern {@code "'{0}'"}.
+ *
+ * <p>Any curly braces within an unquoted pattern must be balanced. For
+ * example, <code>"ab {0} de"</code> and <code>"ab '}' de"</code> are
+ * valid patterns, but <code>"ab {0'}' de"</code>, <code>"ab } de"</code>
+ * and <code>"''{''"</code> are not.
+ *
  * <p>
  * <dl><dt><b>Warning:</b><dd>The rules for using quotes within message
  * format patterns unfortunately have shown to be somewhat confusing.
  * In particular, it isn't always obvious to localizers whether single
  * quotes need to be doubled or not. Make sure to inform localizers about
  * the rules, and tell them (for example, by using comments in resource
- * bundle source files) which strings will be processed by MessageFormat.
+ * bundle source files) which strings will be processed by {@code MessageFormat}.
  * Note that localizers may need to use single quotes in translated
  * strings where the original version doesn't have them.
  * </dl>
  * <p>
  * The <i>ArgumentIndex</i> value is a non-negative integer written
- * using the digits '0' through '9', and represents an index into the
- * <code>arguments</code> array passed to the <code>format</code> methods
- * or the result array returned by the <code>parse</code> methods.
+ * using the digits {@code '0'} through {@code '9'}, and represents an index into the
+ * {@code arguments} array passed to the {@code format} methods
+ * or the result array returned by the {@code parse} methods.
  * <p>
  * The <i>FormatType</i> and <i>FormatStyle</i> values are used to create
- * a <code>Format</code> instance for the format element. The following
- * table shows how the values map to Format instances. Combinations not
+ * a {@code Format} instance for the format element. The following
+ * table shows how the values map to {@code Format} instances. Combinations not
  * shown in the table are illegal. A <i>SubformatPattern</i> must
- * be a valid pattern string for the Format subclass used.
+ * be a valid pattern string for the {@code Format} subclass used.
  * <p>
  * <table border=1 summary="Shows how FormatType and FormatStyle values map to Format instances">
  *    <tr>
- *       <th id="ft">Format Type
- *       <th id="fs">Format Style
- *       <th id="sc">Subformat Created
+ *       <th id="ft" class="TableHeadingColor">FormatType
+ *       <th id="fs" class="TableHeadingColor">FormatStyle
+ *       <th id="sc" class="TableHeadingColor">Subformat Created
  *    <tr>
  *       <td headers="ft"><i>(none)</i>
  *       <td headers="fs"><i>(none)</i>
@@ -167,61 +159,61 @@
  *    <tr>
  *       <td headers="ft" rowspan=5><code>number</code>
  *       <td headers="fs"><i>(none)</i>
- *       <td headers="sc"><code>NumberFormat.getInstance(getLocale())</code>
+ *       <td headers="sc">{@link NumberFormat#getInstance(Locale) NumberFormat.getInstance}{@code (getLocale())}
  *    <tr>
  *       <td headers="fs"><code>integer</code>
- *       <td headers="sc"><code>NumberFormat.getIntegerInstance(getLocale())</code>
+ *       <td headers="sc">{@link NumberFormat#getIntegerInstance(Locale) NumberFormat.getIntegerInstance}{@code (getLocale())}
  *    <tr>
  *       <td headers="fs"><code>currency</code>
- *       <td headers="sc"><code>NumberFormat.getCurrencyInstance(getLocale())</code>
+ *       <td headers="sc">{@link NumberFormat#getCurrencyInstance(Locale) NumberFormat.getCurrencyInstance}{@code (getLocale())}
  *    <tr>
  *       <td headers="fs"><code>percent</code>
- *       <td headers="sc"><code>NumberFormat.getPercentInstance(getLocale())</code>
+ *       <td headers="sc">{@link NumberFormat#getPercentInstance(Locale) NumberFormat.getPercentInstance}{@code (getLocale())}
  *    <tr>
  *       <td headers="fs"><i>SubformatPattern</i>
- *       <td headers="sc"><code>new DecimalFormat(subformatPattern, DecimalFormatSymbols.getInstance(getLocale()))</code>
+ *       <td headers="sc">{@code new} {@link DecimalFormat#DecimalFormat(String,DecimalFormatSymbols) DecimalFormat}{@code (subformatPattern,} {@link DecimalFormatSymbols#getInstance(Locale) DecimalFormatSymbols.getInstance}{@code (getLocale()))}
  *    <tr>
  *       <td headers="ft" rowspan=6><code>date</code>
  *       <td headers="fs"><i>(none)</i>
- *       <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale())</code>
+ *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
  *    <tr>
  *       <td headers="fs"><code>short</code>
- *       <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.SHORT, getLocale())</code>
+ *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#SHORT}{@code , getLocale())}
  *    <tr>
  *       <td headers="fs"><code>medium</code>
- *       <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale())</code>
+ *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
  *    <tr>
  *       <td headers="fs"><code>long</code>
- *       <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.LONG, getLocale())</code>
+ *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#LONG}{@code , getLocale())}
  *    <tr>
  *       <td headers="fs"><code>full</code>
- *       <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.FULL, getLocale())</code>
+ *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#FULL}{@code , getLocale())}
  *    <tr>
  *       <td headers="fs"><i>SubformatPattern</i>
- *       <td headers="sc"><code>new SimpleDateFormat(subformatPattern, getLocale())</code>
+ *       <td headers="sc">{@code new} {@link SimpleDateFormat#SimpleDateFormat(String,Locale) SimpleDateFormat}{@code (subformatPattern, getLocale())}
  *    <tr>
  *       <td headers="ft" rowspan=6><code>time</code>
  *       <td headers="fs"><i>(none)</i>
- *       <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale())</code>
+ *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
  *    <tr>
  *       <td headers="fs"><code>short</code>
- *       <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.SHORT, getLocale())</code>
+ *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#SHORT}{@code , getLocale())}
  *    <tr>
  *       <td headers="fs"><code>medium</code>
- *       <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale())</code>
+ *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
  *    <tr>
  *       <td headers="fs"><code>long</code>
- *       <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.LONG, getLocale())</code>
+ *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#LONG}{@code , getLocale())}
  *    <tr>
  *       <td headers="fs"><code>full</code>
- *       <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.FULL, getLocale())</code>
+ *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#FULL}{@code , getLocale())}
  *    <tr>
  *       <td headers="fs"><i>SubformatPattern</i>
- *       <td headers="sc"><code>new SimpleDateFormat(subformatPattern, getLocale())</code>
+ *       <td headers="sc">{@code new} {@link SimpleDateFormat#SimpleDateFormat(String,Locale) SimpleDateFormat}{@code (subformatPattern, getLocale())}
  *    <tr>
  *       <td headers="ft"><code>choice</code>
  *       <td headers="fs"><i>SubformatPattern</i>
- *       <td headers="sc"><code>new ChoiceFormat(subformatPattern)</code>
+ *       <td headers="sc">{@code new} {@link ChoiceFormat#ChoiceFormat(String) ChoiceFormat}{@code (subformatPattern)}
  * </table>
  * <p>
  *
@@ -321,7 +313,7 @@
  * </pre></blockquote>
  *
  * <p>
- * Likewise, parsing with a MessageFormat object using patterns containing
+ * Likewise, parsing with a {@code MessageFormat} object using patterns containing
  * multiple occurrences of the same argument would return the last match.  For
  * example,
  * <blockquote><pre>
@@ -343,7 +335,11 @@
  * @see          Format
  * @see          NumberFormat
  * @see          DecimalFormat
+ * @see          DecimalFormatSymbols
  * @see          ChoiceFormat
+ * @see          DateFormat
+ * @see          SimpleDateFormat
+ *
  * @author       Mark Davis
  */
 
@@ -427,18 +423,19 @@
      * @exception IllegalArgumentException if the pattern is invalid
      */
     public void applyPattern(String pattern) {
-            StringBuffer[] segments = new StringBuffer[4];
-            for (int i = 0; i < segments.length; ++i) {
-                segments[i] = new StringBuffer();
-            }
-            int part = 0;
+            StringBuilder[] segments = new StringBuilder[4];
+            // Allocate only segments[SEG_RAW] here. The rest are
+            // allocated on demand.
+            segments[SEG_RAW] = new StringBuilder();
+
+            int part = SEG_RAW;
             int formatNumber = 0;
             boolean inQuote = false;
             int braceStack = 0;
             maxOffset = -1;
             for (int i = 0; i < pattern.length(); ++i) {
                 char ch = pattern.charAt(i);
-                if (part == 0) {
+                if (part == SEG_RAW) {
                     if (ch == '\'') {
                         if (i + 1 < pattern.length()
                             && pattern.charAt(i+1) == '\'') {
@@ -448,43 +445,61 @@
                             inQuote = !inQuote;
                         }
                     } else if (ch == '{' && !inQuote) {
-                        part = 1;
+                        part = SEG_INDEX;
+                        if (segments[SEG_INDEX] == null) {
+                            segments[SEG_INDEX] = new StringBuilder();
+                        }
                     } else {
                         segments[part].append(ch);
                     }
-                } else  if (inQuote) {              // just copy quotes in parts
-                    segments[part].append(ch);
-                    if (ch == '\'') {
-                        inQuote = false;
-                    }
-                } else {
-                    switch (ch) {
-                    case ',':
-                        if (part < 3)
-                            part += 1;
-                        else
-                            segments[part].append(ch);
-                        break;
-                    case '{':
-                        ++braceStack;
+                } else  {
+                    if (inQuote) {              // just copy quotes in parts
                         segments[part].append(ch);
-                        break;
-                    case '}':
-                        if (braceStack == 0) {
-                            part = 0;
-                            makeFormat(i, formatNumber, segments);
-                            formatNumber++;
-                        } else {
-                            --braceStack;
-                            segments[part].append(ch);
+                        if (ch == '\'') {
+                            inQuote = false;
                         }
-                        break;
-                    case '\'':
-                        inQuote = true;
-                        // fall through, so we keep quotes in other parts
-                    default:
-                        segments[part].append(ch);
-                        break;
+                    } else {
+                        switch (ch) {
+                        case ',':
+                            if (part < SEG_MODIFIER) {
+                                if (segments[++part] == null) {
+                                    segments[part] = new StringBuilder();
+                                }
+                            } else {
+                                segments[part].append(ch);
+                            }
+                            break;
+                        case '{':
+                            ++braceStack;
+                            segments[part].append(ch);
+                            break;
+                        case '}':
+                            if (braceStack == 0) {
+                                part = SEG_RAW;
+                                makeFormat(i, formatNumber, segments);
+                                formatNumber++;
+                                // throw away other segments
+                                segments[SEG_INDEX] = null;
+                                segments[SEG_TYPE] = null;
+                                segments[SEG_MODIFIER] = null;
+                            } else {
+                                --braceStack;
+                                segments[part].append(ch);
+                            }
+                            break;
+                        case ' ':
+                            // Skip any leading space chars for SEG_TYPE.
+                            if (part != SEG_TYPE || segments[SEG_TYPE].length() > 0) {
+                                segments[part].append(ch);
+                            }
+                            break;
+                        case '\'':
+                            inQuote = true;
+                            // fall through, so we keep quotes in other parts
+                        default:
+                            segments[part].append(ch);
+                            break;
+                        }
                     }
                 }
             }
@@ -506,65 +521,57 @@
     public String toPattern() {
         // later, make this more extensible
         int lastOffset = 0;
-        StringBuffer result = new StringBuffer();
+        StringBuilder result = new StringBuilder();
         for (int i = 0; i <= maxOffset; ++i) {
-            copyAndFixQuotes(pattern, lastOffset, offsets[i],result);
+            copyAndFixQuotes(pattern, lastOffset, offsets[i], result);
             lastOffset = offsets[i];
-            result.append('{');
-            result.append(argumentNumbers[i]);
-            if (formats[i] == null) {
+            result.append('{').append(argumentNumbers[i]);
+            Format fmt = formats[i];
+            if (fmt == null) {
                 // do nothing, string format
-            } else if (formats[i] instanceof DecimalFormat) {
-                if (formats[i].equals(NumberFormat.getInstance(locale))) {
+            } else if (fmt instanceof NumberFormat) {
+                if (fmt.equals(NumberFormat.getInstance(locale))) {
                     result.append(",number");
-                } else if (formats[i].equals(NumberFormat.getCurrencyInstance(locale))) {
+                } else if (fmt.equals(NumberFormat.getCurrencyInstance(locale))) {
                     result.append(",number,currency");
-                } else if (formats[i].equals(NumberFormat.getPercentInstance(locale))) {
+                } else if (fmt.equals(NumberFormat.getPercentInstance(locale))) {
                     result.append(",number,percent");
-                } else if (formats[i].equals(NumberFormat.getIntegerInstance(locale))) {
+                } else if (fmt.equals(NumberFormat.getIntegerInstance(locale))) {
                     result.append(",number,integer");
                 } else {
-                    result.append(",number," +
-                                  ((DecimalFormat)formats[i]).toPattern());
+                    if (fmt instanceof DecimalFormat) {
+                        result.append(",number,").append(((DecimalFormat)fmt).toPattern());
+                    } else if (fmt instanceof ChoiceFormat) {
+                        result.append(",choice,").append(((ChoiceFormat)fmt).toPattern());
+                    } else {
+                        // UNKNOWN
+                    }
                 }
-            } else if (formats[i] instanceof SimpleDateFormat) {
-                if (formats[i].equals(DateFormat.getDateInstance(
-                                                               DateFormat.DEFAULT,locale))) {
-                    result.append(",date");
-                } else if (formats[i].equals(DateFormat.getDateInstance(
-                                                                      DateFormat.SHORT,locale))) {
-                    result.append(",date,short");
-                } else if (formats[i].equals(DateFormat.getDateInstance(
-                                                                      DateFormat.DEFAULT,locale))) {
-                    result.append(",date,medium");
-                } else if (formats[i].equals(DateFormat.getDateInstance(
-                                                                      DateFormat.LONG,locale))) {
-                    result.append(",date,long");
-                } else if (formats[i].equals(DateFormat.getDateInstance(
-                                                                      DateFormat.FULL,locale))) {
-                    result.append(",date,full");
-                } else if (formats[i].equals(DateFormat.getTimeInstance(
-                                                                      DateFormat.DEFAULT,locale))) {
-                    result.append(",time");
-                } else if (formats[i].equals(DateFormat.getTimeInstance(
-                                                                      DateFormat.SHORT,locale))) {
-                    result.append(",time,short");
-                } else if (formats[i].equals(DateFormat.getTimeInstance(
-                                                                      DateFormat.DEFAULT,locale))) {
-                    result.append(",time,medium");
-                } else if (formats[i].equals(DateFormat.getTimeInstance(
-                                                                      DateFormat.LONG,locale))) {
-                    result.append(",time,long");
-                } else if (formats[i].equals(DateFormat.getTimeInstance(
-                                                                      DateFormat.FULL,locale))) {
-                    result.append(",time,full");
-                } else {
-                    result.append(",date,"
-                                  + ((SimpleDateFormat)formats[i]).toPattern());
+            } else if (fmt instanceof DateFormat) {
+                int index;
+                for (index = MODIFIER_DEFAULT; index < DATE_TIME_MODIFIERS.length; index++) {
+                    DateFormat df = DateFormat.getDateInstance(DATE_TIME_MODIFIERS[index],
+                                                               locale);
+                    if (fmt.equals(df)) {
+                        result.append(",date");
+                        break;
+                    }
+                    df = DateFormat.getTimeInstance(DATE_TIME_MODIFIERS[index],
+                                                    locale);
+                    if (fmt.equals(df)) {
+                        result.append(",time");
+                        break;
+                    }
                 }
-            } else if (formats[i] instanceof ChoiceFormat) {
-                result.append(",choice,"
-                              + ((ChoiceFormat)formats[i]).toPattern());
+                if (index >= DATE_TIME_MODIFIERS.length) {
+                    if (fmt instanceof SimpleDateFormat) {
+                        result.append(",date,").append(((SimpleDateFormat)fmt).toPattern());
+                    } else {
+                        // UNKNOWN
+                    }
+                } else if (index != MODIFIER_DEFAULT) {
+                    result.append(',').append(DATE_TIME_MODIFIER_KEYWORDS[index]);
+                }
             } else {
                 //result.append(", unknown");
             }
@@ -678,7 +685,7 @@
      *
      * @param formatElementIndex the index of a format element within the pattern
      * @param newFormat the format to use for the specified format element
-     * @exception ArrayIndexOutOfBoundsException if formatElementIndex is equal to or
+     * @exception ArrayIndexOutOfBoundsException if {@code formatElementIndex} is equal to or
      *            larger than the number of format elements in the pattern string
      */
     public void setFormat(int formatElementIndex, Format newFormat) {
@@ -972,7 +979,8 @@
                 if (patternOffset >= tempLength) {
                     next = source.length();
                 }else{
-                    next = source.indexOf( pattern.substring(patternOffset,tempLength), sourceOffset);
+                    next = source.indexOf(pattern.substring(patternOffset, tempLength),
+                                          sourceOffset);
                 }
 
                 if (next < 0) {
@@ -1226,7 +1234,7 @@
             lastOffset = offsets[i];
             int argumentNumber = argumentNumbers[i];
             if (arguments == null || argumentNumber >= arguments.length) {
-                result.append("{" + argumentNumber + "}");
+                result.append('{').append(argumentNumber).append('}');
                 continue;
             }
             // int argRecursion = ((recursionProtection >> (argumentNumber*2)) & 0x3);
@@ -1338,25 +1346,83 @@
         }
     }
 
-    private static final String[] typeList =
-    {"", "", "number", "", "date", "", "time", "", "choice"};
-    private static final String[] modifierList =
-    {"", "", "currency", "", "percent", "", "integer"};
-    private static final String[] dateModifierList =
-    {"", "", "short", "", "medium", "", "long", "", "full"};
+    // Indices for segments
+    private static final int SEG_RAW      = 0;
+    private static final int SEG_INDEX    = 1;
+    private static final int SEG_TYPE     = 2;
+    private static final int SEG_MODIFIER = 3; // modifier or subformat
+
+    // Indices for type keywords
+    private static final int TYPE_NULL    = 0;
+    private static final int TYPE_NUMBER  = 1;
+    private static final int TYPE_DATE    = 2;
+    private static final int TYPE_TIME    = 3;
+    private static final int TYPE_CHOICE  = 4;
+
+    private static final String[] TYPE_KEYWORDS = {
+        "",
+        "number",
+        "date",
+        "time",
+        "choice"
+    };
+
+    // Indices for number modifiers
+    private static final int MODIFIER_DEFAULT  = 0; // common in number and date-time
+    private static final int MODIFIER_CURRENCY = 1;
+    private static final int MODIFIER_PERCENT  = 2;
+    private static final int MODIFIER_INTEGER  = 3;
+
+    private static final String[] NUMBER_MODIFIER_KEYWORDS = {
+        "",
+        "currency",
+        "percent",
+        "integer"
+    };
+
+    // Indices for date-time modifiers
+    private static final int MODIFIER_SHORT   = 1;
+    private static final int MODIFIER_MEDIUM  = 2;
+    private static final int MODIFIER_LONG    = 3;
+    private static final int MODIFIER_FULL    = 4;
+
+    private static final String[] DATE_TIME_MODIFIER_KEYWORDS = {
+        "",
+        "short",
+        "medium",
+        "long",
+        "full"
+    };
+
+    // Date-time style values corresponding to the date-time modifiers.
+    private static final int[] DATE_TIME_MODIFIERS = {
+        DateFormat.DEFAULT,
+        DateFormat.SHORT,
+        DateFormat.MEDIUM,
+        DateFormat.LONG,
+        DateFormat.FULL,
+    };
 
     private void makeFormat(int position, int offsetNumber,
-                            StringBuffer[] segments)
+                            StringBuilder[] textSegments)
     {
+        String[] segments = new String[textSegments.length];
+        for (int i = 0; i < textSegments.length; i++) {
+            StringBuilder oneseg = textSegments[i];
+            segments[i] = (oneseg != null) ? oneseg.toString() : "";
+        }
+
         // get the argument number
         int argumentNumber;
         try {
-            argumentNumber = Integer.parseInt(segments[1].toString()); // always unlocalized!
+            argumentNumber = Integer.parseInt(segments[SEG_INDEX]); // always unlocalized!
         } catch (NumberFormatException e) {
-            throw new IllegalArgumentException("can't parse argument number: " + segments[1]);
+            throw new IllegalArgumentException("can't parse argument number: "
+                                               + segments[SEG_INDEX], e);
         }
         if (argumentNumber < 0) {
-            throw new IllegalArgumentException("negative argument number: " + argumentNumber);
+            throw new IllegalArgumentException("negative argument number: "
+                                               + argumentNumber);
         }
 
         // resize format information arrays if necessary
@@ -1374,120 +1440,129 @@
         }
         int oldMaxOffset = maxOffset;
         maxOffset = offsetNumber;
-        offsets[offsetNumber] = segments[0].length();
+        offsets[offsetNumber] = segments[SEG_RAW].length();
         argumentNumbers[offsetNumber] = argumentNumber;
 
         // now get the format
         Format newFormat = null;
-        switch (findKeyword(segments[2].toString(), typeList)) {
-        case 0:
-            break;
-        case 1: case 2:// number
-            switch (findKeyword(segments[3].toString(), modifierList)) {
-            case 0: // default;
-                newFormat = NumberFormat.getInstance(locale);
+        if (segments[SEG_TYPE].length() != 0) {
+            int type = findKeyword(segments[SEG_TYPE], TYPE_KEYWORDS);
+            switch (type) {
+            case TYPE_NULL:
+                // Type "" is allowed. e.g., "{0,}", "{0,,}", and "{0,,#}"
+                // are treated as "{0}".
                 break;
-            case 1: case 2:// currency
-                newFormat = NumberFormat.getCurrencyInstance(locale);
+
+            case TYPE_NUMBER:
+                switch (findKeyword(segments[SEG_MODIFIER], NUMBER_MODIFIER_KEYWORDS)) {
+                case MODIFIER_DEFAULT:
+                    newFormat = NumberFormat.getInstance(locale);
+                    break;
+                case MODIFIER_CURRENCY:
+                    newFormat = NumberFormat.getCurrencyInstance(locale);
+                    break;
+                case MODIFIER_PERCENT:
+                    newFormat = NumberFormat.getPercentInstance(locale);
+                    break;
+                case MODIFIER_INTEGER:
+                    newFormat = NumberFormat.getIntegerInstance(locale);
+                    break;
+                default: // DecimalFormat pattern
+                    try {
+                        newFormat = new DecimalFormat(segments[SEG_MODIFIER],
+                                                      DecimalFormatSymbols.getInstance(locale));
+                    } catch (IllegalArgumentException e) {
+                        maxOffset = oldMaxOffset;
+                        throw e;
+                    }
+                    break;
+                }
                 break;
-            case 3: case 4:// percent
-                newFormat = NumberFormat.getPercentInstance(locale);
+
+            case TYPE_DATE:
+            case TYPE_TIME:
+                int mod = findKeyword(segments[SEG_MODIFIER], DATE_TIME_MODIFIER_KEYWORDS);
+                if (mod >= 0 && mod < DATE_TIME_MODIFIER_KEYWORDS.length) {
+                    if (type == TYPE_DATE) {
+                        newFormat = DateFormat.getDateInstance(DATE_TIME_MODIFIERS[mod],
+                                                               locale);
+                    } else {
+                        newFormat = DateFormat.getTimeInstance(DATE_TIME_MODIFIERS[mod],
+                                                               locale);
+                    }
+                } else {
+                    // SimpleDateFormat pattern
+                    try {
+                        newFormat = new SimpleDateFormat(segments[SEG_MODIFIER], locale);
+                    } catch (IllegalArgumentException e) {
+                        maxOffset = oldMaxOffset;
+                        throw e;
+                    }
+                }
                 break;
-            case 5: case 6:// integer
-                newFormat = NumberFormat.getIntegerInstance(locale);
+
+            case TYPE_CHOICE:
+                try {
+                    // ChoiceFormat pattern
+                    newFormat = new ChoiceFormat(segments[SEG_MODIFIER]);
+                } catch (Exception e) {
+                    maxOffset = oldMaxOffset;
+                    throw new IllegalArgumentException("Choice Pattern incorrect: "
+                                                       + segments[SEG_MODIFIER], e);
+                }
                 break;
-            default: // pattern
-                newFormat = new DecimalFormat(segments[3].toString(), DecimalFormatSymbols.getInstance(locale));
-                break;
-            }
-            break;
-        case 3: case 4: // date
-            switch (findKeyword(segments[3].toString(), dateModifierList)) {
-            case 0: // default
-                newFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
-                break;
-            case 1: case 2: // short
-                newFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
-                break;
-            case 3: case 4: // medium
-                newFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
-                break;
-            case 5: case 6: // long
-                newFormat = DateFormat.getDateInstance(DateFormat.LONG, locale);
-                break;
-            case 7: case 8: // full
-                newFormat = DateFormat.getDateInstance(DateFormat.FULL, locale);
-                break;
+
             default:
-                newFormat = new SimpleDateFormat(segments[3].toString(), locale);
-                break;
-            }
-            break;
-        case 5: case 6:// time
-            switch (findKeyword(segments[3].toString(), dateModifierList)) {
-            case 0: // default
-                newFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
-                break;
-            case 1: case 2: // short
-                newFormat = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
-                break;
-            case 3: case 4: // medium
-                newFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
-                break;
-            case 5: case 6: // long
-                newFormat = DateFormat.getTimeInstance(DateFormat.LONG, locale);
-                break;
-            case 7: case 8: // full
-                newFormat = DateFormat.getTimeInstance(DateFormat.FULL, locale);
-                break;
-            default:
-                newFormat = new SimpleDateFormat(segments[3].toString(), locale);
-                break;
-            }
-            break;
-        case 7: case 8:// choice
-            try {
-                newFormat = new ChoiceFormat(segments[3].toString());
-            } catch (Exception e) {
                 maxOffset = oldMaxOffset;
-                throw new IllegalArgumentException(
-                                         "Choice Pattern incorrect");
+                throw new IllegalArgumentException("unknown format type: " +
+                                                   segments[SEG_TYPE]);
             }
-            break;
-        default:
-            maxOffset = oldMaxOffset;
-            throw new IllegalArgumentException("unknown format type: " +
-                                               segments[2].toString());
         }
         formats[offsetNumber] = newFormat;
-        segments[1].setLength(0);   // throw away other segments
-        segments[2].setLength(0);
-        segments[3].setLength(0);
     }
 
     private static final int findKeyword(String s, String[] list) {
-        s = s.trim().toLowerCase();
         for (int i = 0; i < list.length; ++i) {
             if (s.equals(list[i]))
                 return i;
         }
+
+        // Try trimmed lowercase.
+        String ls = s.trim().toLowerCase(Locale.ROOT);
+        if (ls != s) {
+            for (int i = 0; i < list.length; ++i) {
+                if (ls.equals(list[i]))
+                    return i;
+            }
+        }
         return -1;
     }
 
-    private static final void copyAndFixQuotes(
-                                               String source, int start, int end, StringBuffer target) {
+    private static final void copyAndFixQuotes(String source, int start, int end,
+                                               StringBuilder target) {
+        boolean quoted = false;
+
         for (int i = start; i < end; ++i) {
             char ch = source.charAt(i);
             if (ch == '{') {
-                target.append("'{'");
-            } else if (ch == '}') {
-                target.append("'}'");
+                if (!quoted) {
+                    target.append('\'');
+                    quoted = true;
+                }
+                target.append(ch);
             } else if (ch == '\'') {
                 target.append("''");
             } else {
+                if (quoted) {
+                    target.append('\'');
+                    quoted = false;
+                }
                 target.append(ch);
             }
         }
+        if (quoted) {
+            target.append('\'');
+        }
     }
 
     /**
diff --git a/src/share/classes/java/text/SimpleDateFormat.java b/src/share/classes/java/text/SimpleDateFormat.java
index 9ae84f8..fd2876a 100644
--- a/src/share/classes/java/text/SimpleDateFormat.java
+++ b/src/share/classes/java/text/SimpleDateFormat.java
@@ -1663,6 +1663,81 @@
     }
 
     /**
+     * Parses numeric forms of time zone offset, such as "hh:mm", and
+     * sets calb to the parsed value.
+     *
+     * @param text  the text to be parsed
+     * @param start the character position to start parsing
+     * @param sign  1: positive; -1: negative
+     * @param count 0: 'Z' or "GMT+hh:mm" parsing; 1 - 3: the number of 'X's
+     * @param colon true - colon required between hh and mm; false - no colon required
+     * @param calb  a CalendarBuilder in which the parsed value is stored
+     * @return updated parsed position, or its negative value to indicate a parsing error
+     */
+    private int subParseNumericZone(String text, int start, int sign, int count,
+                                    boolean colon, CalendarBuilder calb) {
+        int index = start;
+
+      parse:
+        try {
+            char c = text.charAt(index++);
+            // Parse hh
+            int hours;
+            if (!isDigit(c)) {
+                break parse;
+            }
+            hours = c - '0';
+            c = text.charAt(index++);
+            if (isDigit(c)) {
+                hours = hours * 10 + (c - '0');
+            } else {
+                // If no colon in RFC 822 or 'X' (ISO), two digits are
+                // required.
+                if (count > 0 || !colon) {
+                    break parse;
+                }
+                --index;
+            }
+            if (hours > 23) {
+                break parse;
+            }
+            int minutes = 0;
+            if (count != 1) {
+                // Proceed with parsing mm
+                c = text.charAt(index++);
+                if (colon) {
+                    if (c != ':') {
+                        break parse;
+                    }
+                    c = text.charAt(index++);
+                }
+                if (!isDigit(c)) {
+                    break parse;
+                }
+                minutes = c - '0';
+                c = text.charAt(index++);
+                if (!isDigit(c)) {
+                    break parse;
+                }
+                minutes = minutes * 10 + (c - '0');
+                if (minutes > 59) {
+                    break parse;
+                }
+            }
+            minutes += hours * 60;
+            calb.set(Calendar.ZONE_OFFSET, minutes * MILLIS_PER_MINUTE * sign)
+                .set(Calendar.DST_OFFSET, 0);
+            return index;
+        } catch (IndexOutOfBoundsException e) {
+        }
+        return  1 - index; // -(index - 1)
+    }
+
+    private boolean isDigit(char c) {
+        return c >= '0' && c <= '9';
+    }
+
+    /**
      * Private member function that converts the parsed date strings into
      * timeFields. Returns -start (for ParsePosition) if failed.
      * @param text the time text to be parsed.
@@ -1907,248 +1982,95 @@
 
             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
-                // characters of GMT+/-hh:mm etc.
                 {
                     int sign = 0;
-                    int offset;
-
-                    // For time zones that have no known names, look for strings
-                    // of the form:
-                    //    GMT[+-]hours:minutes or
-                    //    GMT.
-                    if ((text.length() - start) >= GMT.length() &&
-                        text.regionMatches(true, start, GMT, 0, GMT.length())) {
-                        int num;
-                        calb.set(Calendar.DST_OFFSET, 0);
-                        pos.index = start + GMT.length();
-
-                        try { // try-catch for "GMT" only time zone string
-                            char c = text.charAt(pos.index);
-                            if (c == '+') {
-                                sign = 1;
-                            } else if (c == '-') {
-                                sign = -1;
-                            }
+                    try {
+                        char c = text.charAt(pos.index);
+                        if (c == '+') {
+                            sign = 1;
+                        } else if (c == '-') {
+                            sign = -1;
                         }
-                        catch(StringIndexOutOfBoundsException e) {}
+                        if (sign == 0) {
+                            // Try parsing a custom time zone "GMT+hh:mm" or "GMT".
+                            if ((c == 'G' || c == 'g')
+                                && (text.length() - start) >= GMT.length()
+                                && text.regionMatches(true, start, GMT, 0, GMT.length())) {
+                                pos.index = start + GMT.length();
 
-                        if (sign == 0) {    /* "GMT" without offset */
-                            calb.set(Calendar.ZONE_OFFSET, 0);
-                            return pos.index;
-                        }
-
-                        // Look for hours.
-                        try {
-                            char c = text.charAt(++pos.index);
-                            if (c < '0' || c > '9') { /* must be from '0' to '9'. */
-                                break parsing;
-                            }
-                            num = c - '0';
-
-                            if (text.charAt(++pos.index) != ':') {
-                                c = text.charAt(pos.index);
-                                if (c < '0' || c > '9') { /* must be from '0' to '9'. */
-                                    break parsing;
+                                if ((text.length() - pos.index) > 0) {
+                                    c = text.charAt(pos.index);
+                                    if (c == '+') {
+                                        sign = 1;
+                                    } else if (c == '-') {
+                                        sign = -1;
+                                    }
                                 }
-                                num *= 10;
-                                num += c - '0';
-                                pos.index++;
-                            }
-                            if (num > 23) {
-                                --pos.index;
-                                break parsing;
-                            }
-                            if  (text.charAt(pos.index) != ':') {
-                                break parsing;
-                            }
 
-                            // Look for minutes.
-                            offset = num * 60;
-                            c = text.charAt(++pos.index);
-                            if (c < '0' || c > '9') { /* must be from '0' to '9'. */
-                                break parsing;
-                            }
-                            num = c - '0';
-                            c = text.charAt(++pos.index);
-                            if (c < '0' || c > '9') { /* must be from '0' to '9'. */
-                                break parsing;
-                            }
-                            num *= 10;
-                            num += c - '0';
+                                if (sign == 0) {    /* "GMT" without offset */
+                                    calb.set(Calendar.ZONE_OFFSET, 0)
+                                        .set(Calendar.DST_OFFSET, 0);
+                                    return pos.index;
+                                }
 
-                            if (num > 59) {
-                                break parsing;
-                            }
-                        } catch (StringIndexOutOfBoundsException e) {
-                            break parsing;
-                        }
-                        offset += num;
-                        // Fall through for final processing below of 'offset' and 'sign'.
-                    } else {
-                        // If the first character is a sign, look for numeric timezones of
-                        // the form [+-]hhmm as specified by RFC 822. Otherwise, check
-                        // for named time zones by looking through the locale data from
-                        // the TimeZoneNames strings.
-                        try {
-                            char c = text.charAt(pos.index);
-                            if (c == '+') {
-                                sign = 1;
-                            } else if (c == '-') {
-                                sign = -1;
-                            } else {
-                                // Try parsing the text as a time zone name (abbr).
-                                int i = subParseZoneString(text, pos.index, calb);
-                                if (i != 0) {
+                                // Parse the rest as "hh:mm"
+                                int i = subParseNumericZone(text, ++pos.index,
+                                                            sign, 0, true, calb);
+                                if (i > 0) {
                                     return i;
                                 }
-                                break parsing;
+                                pos.index = -i;
+                            } else {
+                                // Try parsing the text as a time zone
+                                // name or abbreviation.
+                                int i = subParseZoneString(text, pos.index, calb);
+                                if (i > 0) {
+                                    return i;
+                                }
+                                pos.index = -i;
                             }
-
-                            // Parse the text as an RFC 822 time zone string. This code is
-                            // actually a little more permissive than RFC 822.  It will
-                            // try to do its best with numbers that aren't strictly 4
-                            // digits long.
-
-                            // Look for hh.
-                            int hours = 0;
-                            c = text.charAt(++pos.index);
-                            if (c < '0' || c > '9') { /* must be from '0' to '9'. */
-                                break parsing;
+                        } else {
+                            // Parse the rest as "hhmm" (RFC 822)
+                            int i = subParseNumericZone(text, ++pos.index,
+                                                        sign, 0, false, calb);
+                            if (i > 0) {
+                                return i;
                             }
-                            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;
-                            }
-
-                            // Look for mm.
-                            int minutes = 0;
-                            c = text.charAt(++pos.index);
-                            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;
+                            pos.index = -i;
                         }
-                    }
-
-                    // 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;
+                    } catch (IndexOutOfBoundsException e) {
                     }
                 }
                 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;
-                        }
+                    if ((text.length() - pos.index) <= 0) {
+                        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);
+                    int sign = 0;
+                    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;
+                    } else {
+                        ++pos.index;
+                        break parsing;
+                    }
+                    int i = subParseNumericZone(text, ++pos.index, sign, count,
+                                                count == 3, calb);
+                    if (i > 0) {
+                        return i;
+                    }
+                    pos.index = -i;
                 }
                 break parsing;
 
diff --git a/src/share/classes/java/util/AbstractList.java b/src/share/classes/java/util/AbstractList.java
index 2b49b5e..4492166 100644
--- a/src/share/classes/java/util/AbstractList.java
+++ b/src/share/classes/java/util/AbstractList.java
@@ -482,8 +482,8 @@
      */
     public List<E> subList(int fromIndex, int toIndex) {
         return (this instanceof RandomAccess ?
-                new RandomAccessSubList<E>(this, fromIndex, toIndex) :
-                new SubList<E>(this, fromIndex, toIndex));
+                new RandomAccessSubList<>(this, fromIndex, toIndex) :
+                new SubList<>(this, fromIndex, toIndex));
     }
 
     // Comparison and hashing
@@ -747,7 +747,7 @@
     }
 
     public List<E> subList(int fromIndex, int toIndex) {
-        return new SubList<E>(this, fromIndex, toIndex);
+        return new SubList<>(this, fromIndex, toIndex);
     }
 
     private void rangeCheck(int index) {
@@ -776,6 +776,6 @@
     }
 
     public List<E> subList(int fromIndex, int toIndex) {
-        return new RandomAccessSubList<E>(this, fromIndex, toIndex);
+        return new RandomAccessSubList<>(this, fromIndex, toIndex);
     }
 }
diff --git a/src/share/classes/java/util/Arrays.java b/src/share/classes/java/util/Arrays.java
index ff328f5..6a03fbf 100644
--- a/src/share/classes/java/util/Arrays.java
+++ b/src/share/classes/java/util/Arrays.java
@@ -2824,7 +2824,7 @@
      * @return a list view of the specified array
      */
     public static <T> List<T> asList(T... a) {
-        return new ArrayList<T>(a);
+        return new ArrayList<>(a);
     }
 
     /**
diff --git a/src/share/classes/java/util/Collections.java b/src/share/classes/java/util/Collections.java
index 3664982..08f8adb 100644
--- a/src/share/classes/java/util/Collections.java
+++ b/src/share/classes/java/util/Collections.java
@@ -1035,7 +1035,7 @@
      * @return an unmodifiable view of the specified collection.
      */
     public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
-        return new UnmodifiableCollection<T>(c);
+        return new UnmodifiableCollection<>(c);
     }
 
     /**
@@ -1109,7 +1109,7 @@
      * @return an unmodifiable view of the specified set.
      */
     public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
-        return new UnmodifiableSet<T>(s);
+        return new UnmodifiableSet<>(s);
     }
 
     /**
@@ -1141,7 +1141,7 @@
      * @return an unmodifiable view of the specified sorted set.
      */
     public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
-        return new UnmodifiableSortedSet<T>(s);
+        return new UnmodifiableSortedSet<>(s);
     }
 
     /**
@@ -1158,13 +1158,13 @@
         public Comparator<? super E> comparator() {return ss.comparator();}
 
         public SortedSet<E> subSet(E fromElement, E toElement) {
-            return new UnmodifiableSortedSet<E>(ss.subSet(fromElement,toElement));
+            return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));
         }
         public SortedSet<E> headSet(E toElement) {
-            return new UnmodifiableSortedSet<E>(ss.headSet(toElement));
+            return new UnmodifiableSortedSet<>(ss.headSet(toElement));
         }
         public SortedSet<E> tailSet(E fromElement) {
-            return new UnmodifiableSortedSet<E>(ss.tailSet(fromElement));
+            return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));
         }
 
         public E first()                   {return ss.first();}
@@ -1188,8 +1188,8 @@
      */
     public static <T> List<T> unmodifiableList(List<? extends T> list) {
         return (list instanceof RandomAccess ?
-                new UnmodifiableRandomAccessList<T>(list) :
-                new UnmodifiableList<T>(list));
+                new UnmodifiableRandomAccessList<>(list) :
+                new UnmodifiableList<>(list));
     }
 
     /**
@@ -1250,7 +1250,7 @@
         }
 
         public List<E> subList(int fromIndex, int toIndex) {
-            return new UnmodifiableList<E>(list.subList(fromIndex, toIndex));
+            return new UnmodifiableList<>(list.subList(fromIndex, toIndex));
         }
 
         /**
@@ -1267,7 +1267,7 @@
          */
         private Object readResolve() {
             return (list instanceof RandomAccess
-                    ? new UnmodifiableRandomAccessList<E>(list)
+                    ? new UnmodifiableRandomAccessList<>(list)
                     : this);
         }
     }
@@ -1283,7 +1283,7 @@
         }
 
         public List<E> subList(int fromIndex, int toIndex) {
-            return new UnmodifiableRandomAccessList<E>(
+            return new UnmodifiableRandomAccessList<>(
                 list.subList(fromIndex, toIndex));
         }
 
@@ -1296,7 +1296,7 @@
          * deserialization.
          */
         private Object writeReplace() {
-            return new UnmodifiableList<E>(list);
+            return new UnmodifiableList<>(list);
         }
     }
 
@@ -1315,7 +1315,7 @@
      * @return an unmodifiable view of the specified map.
      */
     public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
-        return new UnmodifiableMap<K,V>(m);
+        return new UnmodifiableMap<>(m);
     }
 
     /**
@@ -1363,7 +1363,7 @@
 
         public Set<Map.Entry<K,V>> entrySet() {
             if (entrySet==null)
-                entrySet = new UnmodifiableEntrySet<K,V>(m.entrySet());
+                entrySet = new UnmodifiableEntrySet<>(m.entrySet());
             return entrySet;
         }
 
@@ -1400,7 +1400,7 @@
                         return i.hasNext();
                     }
                     public Map.Entry<K,V> next() {
-                        return new UnmodifiableEntry<K,V>(i.next());
+                        return new UnmodifiableEntry<>(i.next());
                     }
                     public void remove() {
                         throw new UnsupportedOperationException();
@@ -1411,7 +1411,7 @@
             public Object[] toArray() {
                 Object[] a = c.toArray();
                 for (int i=0; i<a.length; i++)
-                    a[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)a[i]);
+                    a[i] = new UnmodifiableEntry<>((Map.Entry<K,V>)a[i]);
                 return a;
             }
 
@@ -1422,7 +1422,7 @@
                 Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
 
                 for (int i=0; i<arr.length; i++)
-                    arr[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)arr[i]);
+                    arr[i] = new UnmodifiableEntry<>((Map.Entry<K,V>)arr[i]);
 
                 if (arr.length > a.length)
                     return (T[])arr;
@@ -1443,7 +1443,7 @@
                 if (!(o instanceof Map.Entry))
                     return false;
                 return c.contains(
-                    new UnmodifiableEntry<Object,Object>((Map.Entry<?,?>) o));
+                    new UnmodifiableEntry<>((Map.Entry<?,?>) o));
             }
 
             /**
@@ -1517,7 +1517,7 @@
      * @return an unmodifiable view of the specified sorted map.
      */
     public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
-        return new UnmodifiableSortedMap<K,V>(m);
+        return new UnmodifiableSortedMap<>(m);
     }
 
     /**
@@ -1535,13 +1535,13 @@
         public Comparator<? super K> comparator() {return sm.comparator();}
 
         public SortedMap<K,V> subMap(K fromKey, K toKey) {
-            return new UnmodifiableSortedMap<K,V>(sm.subMap(fromKey, toKey));
+            return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey));
         }
         public SortedMap<K,V> headMap(K toKey) {
-            return new UnmodifiableSortedMap<K,V>(sm.headMap(toKey));
+            return new UnmodifiableSortedMap<>(sm.headMap(toKey));
         }
         public SortedMap<K,V> tailMap(K fromKey) {
-            return new UnmodifiableSortedMap<K,V>(sm.tailMap(fromKey));
+            return new UnmodifiableSortedMap<>(sm.tailMap(fromKey));
         }
 
         public K firstKey()           {return sm.firstKey();}
@@ -1583,11 +1583,11 @@
      * @return a synchronized view of the specified collection.
      */
     public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
-        return new SynchronizedCollection<T>(c);
+        return new SynchronizedCollection<>(c);
     }
 
     static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
-        return new SynchronizedCollection<T>(c, mutex);
+        return new SynchronizedCollection<>(c, mutex);
     }
 
     /**
@@ -1686,11 +1686,11 @@
      * @return a synchronized view of the specified set.
      */
     public static <T> Set<T> synchronizedSet(Set<T> s) {
-        return new SynchronizedSet<T>(s);
+        return new SynchronizedSet<>(s);
     }
 
     static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
-        return new SynchronizedSet<T>(s, mutex);
+        return new SynchronizedSet<>(s, mutex);
     }
 
     /**
@@ -1754,7 +1754,7 @@
      * @return a synchronized view of the specified sorted set.
      */
     public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
-        return new SynchronizedSortedSet<T>(s);
+        return new SynchronizedSortedSet<>(s);
     }
 
     /**
@@ -1783,18 +1783,18 @@
 
         public SortedSet<E> subSet(E fromElement, E toElement) {
             synchronized (mutex) {
-                return new SynchronizedSortedSet<E>(
+                return new SynchronizedSortedSet<>(
                     ss.subSet(fromElement, toElement), mutex);
             }
         }
         public SortedSet<E> headSet(E toElement) {
             synchronized (mutex) {
-                return new SynchronizedSortedSet<E>(ss.headSet(toElement), mutex);
+                return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);
             }
         }
         public SortedSet<E> tailSet(E fromElement) {
             synchronized (mutex) {
-               return new SynchronizedSortedSet<E>(ss.tailSet(fromElement),mutex);
+               return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);
             }
         }
 
@@ -1833,14 +1833,14 @@
      */
     public static <T> List<T> synchronizedList(List<T> list) {
         return (list instanceof RandomAccess ?
-                new SynchronizedRandomAccessList<T>(list) :
-                new SynchronizedList<T>(list));
+                new SynchronizedRandomAccessList<>(list) :
+                new SynchronizedList<>(list));
     }
 
     static <T> List<T> synchronizedList(List<T> list, Object mutex) {
         return (list instanceof RandomAccess ?
-                new SynchronizedRandomAccessList<T>(list, mutex) :
-                new SynchronizedList<T>(list, mutex));
+                new SynchronizedRandomAccessList<>(list, mutex) :
+                new SynchronizedList<>(list, mutex));
     }
 
     /**
@@ -1903,7 +1903,7 @@
 
         public List<E> subList(int fromIndex, int toIndex) {
             synchronized (mutex) {
-                return new SynchronizedList<E>(list.subList(fromIndex, toIndex),
+                return new SynchronizedList<>(list.subList(fromIndex, toIndex),
                                             mutex);
             }
         }
@@ -1922,7 +1922,7 @@
          */
         private Object readResolve() {
             return (list instanceof RandomAccess
-                    ? new SynchronizedRandomAccessList<E>(list)
+                    ? new SynchronizedRandomAccessList<>(list)
                     : this);
         }
     }
@@ -1944,7 +1944,7 @@
 
         public List<E> subList(int fromIndex, int toIndex) {
             synchronized (mutex) {
-                return new SynchronizedRandomAccessList<E>(
+                return new SynchronizedRandomAccessList<>(
                     list.subList(fromIndex, toIndex), mutex);
             }
         }
@@ -1958,7 +1958,7 @@
          * deserialization.
          */
         private Object writeReplace() {
-            return new SynchronizedList<E>(list);
+            return new SynchronizedList<>(list);
         }
     }
 
@@ -1990,7 +1990,7 @@
      * @return a synchronized view of the specified map.
      */
     public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
-        return new SynchronizedMap<K,V>(m);
+        return new SynchronizedMap<>(m);
     }
 
     /**
@@ -2051,7 +2051,7 @@
         public Set<K> keySet() {
             synchronized (mutex) {
                 if (keySet==null)
-                    keySet = new SynchronizedSet<K>(m.keySet(), mutex);
+                    keySet = new SynchronizedSet<>(m.keySet(), mutex);
                 return keySet;
             }
         }
@@ -2059,7 +2059,7 @@
         public Set<Map.Entry<K,V>> entrySet() {
             synchronized (mutex) {
                 if (entrySet==null)
-                    entrySet = new SynchronizedSet<Map.Entry<K,V>>(m.entrySet(), mutex);
+                    entrySet = new SynchronizedSet<>(m.entrySet(), mutex);
                 return entrySet;
             }
         }
@@ -2067,7 +2067,7 @@
         public Collection<V> values() {
             synchronized (mutex) {
                 if (values==null)
-                    values = new SynchronizedCollection<V>(m.values(), mutex);
+                    values = new SynchronizedCollection<>(m.values(), mutex);
                 return values;
             }
         }
@@ -2129,7 +2129,7 @@
      * @return a synchronized view of the specified sorted map.
      */
     public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
-        return new SynchronizedSortedMap<K,V>(m);
+        return new SynchronizedSortedMap<>(m);
     }
 
 
@@ -2159,18 +2159,18 @@
 
         public SortedMap<K,V> subMap(K fromKey, K toKey) {
             synchronized (mutex) {
-                return new SynchronizedSortedMap<K,V>(
+                return new SynchronizedSortedMap<>(
                     sm.subMap(fromKey, toKey), mutex);
             }
         }
         public SortedMap<K,V> headMap(K toKey) {
             synchronized (mutex) {
-                return new SynchronizedSortedMap<K,V>(sm.headMap(toKey), mutex);
+                return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex);
             }
         }
         public SortedMap<K,V> tailMap(K fromKey) {
             synchronized (mutex) {
-               return new SynchronizedSortedMap<K,V>(sm.tailMap(fromKey),mutex);
+               return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex);
             }
         }
 
@@ -2246,7 +2246,7 @@
      */
     public static <E> Collection<E> checkedCollection(Collection<E> c,
                                                       Class<E> type) {
-        return new CheckedCollection<E>(c, type);
+        return new CheckedCollection<>(c, type);
     }
 
     @SuppressWarnings("unchecked")
@@ -2378,7 +2378,7 @@
      * @since 1.5
      */
     public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
-        return new CheckedSet<E>(s, type);
+        return new CheckedSet<>(s, type);
     }
 
     /**
@@ -2424,7 +2424,7 @@
      */
     public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
                                                     Class<E> type) {
-        return new CheckedSortedSet<E>(s, type);
+        return new CheckedSortedSet<>(s, type);
     }
 
     /**
@@ -2484,8 +2484,8 @@
      */
     public static <E> List<E> checkedList(List<E> list, Class<E> type) {
         return (list instanceof RandomAccess ?
-                new CheckedRandomAccessList<E>(list, type) :
-                new CheckedList<E>(list, type));
+                new CheckedRandomAccessList<>(list, type) :
+                new CheckedList<>(list, type));
     }
 
     /**
@@ -2550,7 +2550,7 @@
         }
 
         public List<E> subList(int fromIndex, int toIndex) {
-            return new CheckedList<E>(list.subList(fromIndex, toIndex), type);
+            return new CheckedList<>(list.subList(fromIndex, toIndex), type);
         }
     }
 
@@ -2567,7 +2567,7 @@
         }
 
         public List<E> subList(int fromIndex, int toIndex) {
-            return new CheckedRandomAccessList<E>(
+            return new CheckedRandomAccessList<>(
                 list.subList(fromIndex, toIndex), type);
         }
     }
@@ -2609,7 +2609,7 @@
     public static <K, V> Map<K, V> checkedMap(Map<K, V> m,
                                               Class<K> keyType,
                                               Class<V> valueType) {
-        return new CheckedMap<K,V>(m, keyType, valueType);
+        return new CheckedMap<>(m, keyType, valueType);
     }
 
 
@@ -2677,15 +2677,14 @@
             // - protection from malicious t
             // - correct behavior if t is a concurrent map
             Object[] entries = t.entrySet().toArray();
-            List<Map.Entry<K,V>> checked =
-                new ArrayList<Map.Entry<K,V>>(entries.length);
+            List<Map.Entry<K,V>> checked = new ArrayList<>(entries.length);
             for (Object o : entries) {
                 Map.Entry<?,?> e = (Map.Entry<?,?>) o;
                 Object k = e.getKey();
                 Object v = e.getValue();
                 typeCheck(k, v);
                 checked.add(
-                    new AbstractMap.SimpleImmutableEntry<K,V>((K) k, (V) v));
+                    new AbstractMap.SimpleImmutableEntry<>((K) k, (V) v));
             }
             for (Map.Entry<K,V> e : checked)
                 m.put(e.getKey(), e.getValue());
@@ -2695,7 +2694,7 @@
 
         public Set<Map.Entry<K,V>> entrySet() {
             if (entrySet==null)
-                entrySet = new CheckedEntrySet<K,V>(m.entrySet(), valueType);
+                entrySet = new CheckedEntrySet<>(m.entrySet(), valueType);
             return entrySet;
         }
 
@@ -2810,7 +2809,7 @@
                 if (!(o instanceof Map.Entry))
                     return false;
                 return s.remove(new AbstractMap.SimpleImmutableEntry
-                                <Object, Object>((Map.Entry<?,?>)o));
+                                <>((Map.Entry<?,?>)o));
             }
 
             public boolean removeAll(Collection<?> c) {
@@ -2843,7 +2842,7 @@
 
             static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e,
                                                             Class<T> valueType) {
-                return new CheckedEntry<K,V,T>(e, valueType);
+                return new CheckedEntry<>(e, valueType);
             }
 
             /**
@@ -2884,7 +2883,7 @@
                     if (!(o instanceof Map.Entry))
                         return false;
                     return e.equals(new AbstractMap.SimpleImmutableEntry
-                                    <Object, Object>((Map.Entry<?,?>)o));
+                                    <>((Map.Entry<?,?>)o));
                 }
             }
         }
@@ -2927,7 +2926,7 @@
     public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
                                                         Class<K> keyType,
                                                         Class<V> valueType) {
-        return new CheckedSortedMap<K,V>(m, keyType, valueType);
+        return new CheckedSortedMap<>(m, keyType, valueType);
     }
 
     /**
@@ -2993,7 +2992,7 @@
 
     private static class EmptyIterator<E> implements Iterator<E> {
         static final EmptyIterator<Object> EMPTY_ITERATOR
-            = new EmptyIterator<Object>();
+            = new EmptyIterator<>();
 
         public boolean hasNext() { return false; }
         public E next() { throw new NoSuchElementException(); }
@@ -3042,7 +3041,7 @@
         implements ListIterator<E>
     {
         static final EmptyListIterator<Object> EMPTY_ITERATOR
-            = new EmptyListIterator<Object>();
+            = new EmptyListIterator<>();
 
         public boolean hasPrevious() { return false; }
         public E previous() { throw new NoSuchElementException(); }
@@ -3078,7 +3077,7 @@
 
     private static class EmptyEnumeration<E> implements Enumeration<E> {
         static final EmptyEnumeration<Object> EMPTY_ENUMERATION
-            = new EmptyEnumeration<Object>();
+            = new EmptyEnumeration<>();
 
         public boolean hasMoreElements() { return false; }
         public E nextElement() { throw new NoSuchElementException(); }
@@ -3090,7 +3089,7 @@
      * @see #emptySet()
      */
     @SuppressWarnings("unchecked")
-    public static final Set EMPTY_SET = new EmptySet<Object>();
+    public static final Set EMPTY_SET = new EmptySet<>();
 
     /**
      * Returns the empty set (immutable).  This set is serializable.
@@ -3150,7 +3149,7 @@
      * @see #emptyList()
      */
     @SuppressWarnings("unchecked")
-    public static final List EMPTY_LIST = new EmptyList<Object>();
+    public static final List EMPTY_LIST = new EmptyList<>();
 
     /**
      * Returns the empty list (immutable).  This list is serializable.
@@ -3224,7 +3223,7 @@
      * @since 1.3
      */
     @SuppressWarnings("unchecked")
-    public static final Map EMPTY_MAP = new EmptyMap<Object,Object>();
+    public static final Map EMPTY_MAP = new EmptyMap<>();
 
     /**
      * Returns the empty map (immutable).  This map is serializable.
@@ -3286,7 +3285,7 @@
      * @return an immutable set containing only the specified object.
      */
     public static <T> Set<T> singleton(T o) {
-        return new SingletonSet<T>(o);
+        return new SingletonSet<>(o);
     }
 
     static <E> Iterator<E> singletonIterator(final E e) {
@@ -3339,7 +3338,7 @@
      * @since 1.3
      */
     public static <T> List<T> singletonList(T o) {
-        return new SingletonList<T>(o);
+        return new SingletonList<>(o);
     }
 
     /**
@@ -3381,7 +3380,7 @@
      * @since 1.3
      */
     public static <K,V> Map<K,V> singletonMap(K key, V value) {
-        return new SingletonMap<K,V>(key, value);
+        return new SingletonMap<>(key, value);
     }
 
     /**
@@ -3423,7 +3422,7 @@
         public Set<Map.Entry<K,V>> entrySet() {
             if (entrySet==null)
                 entrySet = Collections.<Map.Entry<K,V>>singleton(
-                    new SimpleImmutableEntry<K,V>(k, v));
+                    new SimpleImmutableEntry<>(k, v));
             return entrySet;
         }
 
@@ -3455,7 +3454,7 @@
     public static <T> List<T> nCopies(int n, T o) {
         if (n < 0)
             throw new IllegalArgumentException("List length = " + n);
-        return new CopiesList<T>(n, o);
+        return new CopiesList<>(n, o);
     }
 
     /**
@@ -3529,7 +3528,7 @@
             if (fromIndex > toIndex)
                 throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                                    ") > toIndex(" + toIndex + ")");
-            return new CopiesList<E>(toIndex - fromIndex, element);
+            return new CopiesList<>(toIndex - fromIndex, element);
         }
     }
 
@@ -3595,7 +3594,7 @@
         if (cmp instanceof ReverseComparator2)
             return ((ReverseComparator2<T>)cmp).cmp;
 
-        return new ReverseComparator2<T>(cmp);
+        return new ReverseComparator2<>(cmp);
     }
 
     /**
@@ -3674,7 +3673,7 @@
      * @see ArrayList
      */
     public static <T> ArrayList<T> list(Enumeration<T> e) {
-        ArrayList<T> l = new ArrayList<T>();
+        ArrayList<T> l = new ArrayList<>();
         while (e.hasMoreElements())
             l.add(e.nextElement());
         return l;
@@ -3819,7 +3818,7 @@
      * @since 1.6
      */
     public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
-        return new SetFromMap<E>(map);
+        return new SetFromMap<>(map);
     }
 
     /**
@@ -3883,7 +3882,7 @@
      * @since  1.6
      */
     public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
-        return new AsLIFOQueue<T>(deque);
+        return new AsLIFOQueue<>(deque);
     }
 
     /**
diff --git a/src/share/classes/java/util/EnumMap.java b/src/share/classes/java/util/EnumMap.java
index 589cb97..e48b486 100644
--- a/src/share/classes/java/util/EnumMap.java
+++ b/src/share/classes/java/util/EnumMap.java
@@ -499,7 +499,7 @@
             int j = 0;
             for (int i = 0; i < vals.length; i++)
                 if (vals[i] != null)
-                    a[j++] = new AbstractMap.SimpleEntry<K,V>(
+                    a[j++] = new AbstractMap.SimpleEntry<>(
                         keyUniverse[i], unmaskNull(vals[i]));
             return a;
         }
diff --git a/src/share/classes/java/util/EnumSet.java b/src/share/classes/java/util/EnumSet.java
index 023c5e1..cbf355f 100644
--- a/src/share/classes/java/util/EnumSet.java
+++ b/src/share/classes/java/util/EnumSet.java
@@ -110,9 +110,9 @@
             throw new ClassCastException(elementType + " not an enum");
 
         if (universe.length <= 64)
-            return new RegularEnumSet<E>(elementType, universe);
+            return new RegularEnumSet<>(elementType, universe);
         else
-            return new JumboEnumSet<E>(elementType, universe);
+            return new JumboEnumSet<>(elementType, universe);
     }
 
     /**
@@ -430,7 +430,7 @@
     }
 
     Object writeReplace() {
-        return new SerializationProxy<E>(this);
+        return new SerializationProxy<>(this);
     }
 
     // readObject method for the serialization proxy pattern
diff --git a/src/share/classes/java/util/Formatter.java b/src/share/classes/java/util/Formatter.java
index 0fc63f8..316135e 100644
--- a/src/share/classes/java/util/Formatter.java
+++ b/src/share/classes/java/util/Formatter.java
@@ -2490,7 +2490,7 @@
      * Finds format specifiers in the format string.
      */
     private FormatString[] parse(String s) {
-        ArrayList<FormatString> al = new ArrayList<FormatString>();
+        ArrayList<FormatString> al = new ArrayList<>();
         Matcher m = fsPattern.matcher(s);
         for (int i = 0, len = s.length(); i < len; ) {
             if (m.find(i)) {
diff --git a/src/share/classes/java/util/HashMap.java b/src/share/classes/java/util/HashMap.java
index 8639022..242860f 100644
--- a/src/share/classes/java/util/HashMap.java
+++ b/src/share/classes/java/util/HashMap.java
@@ -763,7 +763,7 @@
      */
     void addEntry(int hash, K key, V value, int bucketIndex) {
         Entry<K,V> e = table[bucketIndex];
-        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
+        table[bucketIndex] = new Entry<>(hash, key, value, e);
         if (size++ >= threshold)
             resize(2 * table.length);
     }
@@ -778,7 +778,7 @@
      */
     void createEntry(int hash, K key, V value, int bucketIndex) {
         Entry<K,V> e = table[bucketIndex];
-        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
+        table[bucketIndex] = new Entry<>(hash, key, value, e);
         size++;
     }
 
diff --git a/src/share/classes/java/util/HashSet.java b/src/share/classes/java/util/HashSet.java
index 1d45d96..4ffaf17 100644
--- a/src/share/classes/java/util/HashSet.java
+++ b/src/share/classes/java/util/HashSet.java
@@ -100,7 +100,7 @@
      * default initial capacity (16) and load factor (0.75).
      */
     public HashSet() {
-        map = new HashMap<E,Object>();
+        map = new HashMap<>();
     }
 
     /**
@@ -113,7 +113,7 @@
      * @throws NullPointerException if the specified collection is null
      */
     public HashSet(Collection<? extends E> c) {
-        map = new HashMap<E,Object>(Math.max((int) (c.size()/.75f) + 1, 16));
+        map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
         addAll(c);
     }
 
@@ -127,7 +127,7 @@
      *             than zero, or if the load factor is nonpositive
      */
     public HashSet(int initialCapacity, float loadFactor) {
-        map = new HashMap<E,Object>(initialCapacity, loadFactor);
+        map = new HashMap<>(initialCapacity, loadFactor);
     }
 
     /**
@@ -139,7 +139,7 @@
      *             than zero
      */
     public HashSet(int initialCapacity) {
-        map = new HashMap<E,Object>(initialCapacity);
+        map = new HashMap<>(initialCapacity);
     }
 
     /**
@@ -156,7 +156,7 @@
      *             than zero, or if the load factor is nonpositive
      */
     HashSet(int initialCapacity, float loadFactor, boolean dummy) {
-        map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);
+        map = new LinkedHashMap<>(initialCapacity, loadFactor);
     }
 
     /**
diff --git a/src/share/classes/java/util/Hashtable.java b/src/share/classes/java/util/Hashtable.java
index 792ebee..63af558 100644
--- a/src/share/classes/java/util/Hashtable.java
+++ b/src/share/classes/java/util/Hashtable.java
@@ -455,7 +455,7 @@
 
         // Creates the new entry.
         Entry<K,V> e = tab[index];
-        tab[index] = new Entry<K,V>(hash, key, value, e);
+        tab[index] = new Entry<>(hash, key, value, e);
         count++;
         return null;
     }
@@ -579,7 +579,7 @@
         if (count == 0) {
             return Collections.emptyEnumeration();
         } else {
-            return new Enumerator<T>(type, false);
+            return new Enumerator<>(type, false);
         }
     }
 
@@ -587,7 +587,7 @@
         if (count == 0) {
             return Collections.emptyIterator();
         } else {
-            return new Enumerator<T>(type, true);
+            return new Enumerator<>(type, true);
         }
     }
 
@@ -929,7 +929,7 @@
         }
         // Creates the new entry.
         Entry<K,V> e = tab[index];
-        tab[index] = new Entry<K,V>(hash, key, value, e);
+        tab[index] = new Entry<>(hash, key, value, e);
         count++;
     }
 
@@ -950,7 +950,7 @@
         }
 
         protected Object clone() {
-            return new Entry<K,V>(hash, key, value,
+            return new Entry<>(hash, key, value,
                                   (next==null ? null : (Entry<K,V>) next.clone()));
         }
 
diff --git a/src/share/classes/java/util/IdentityHashMap.java b/src/share/classes/java/util/IdentityHashMap.java
index a0ffdbe..12109a0 100644
--- a/src/share/classes/java/util/IdentityHashMap.java
+++ b/src/share/classes/java/util/IdentityHashMap.java
@@ -1134,7 +1134,7 @@
             Object[] result = new Object[size];
             Iterator<Map.Entry<K,V>> it = iterator();
             for (int i = 0; i < size; i++)
-                result[i] = new AbstractMap.SimpleEntry<K,V>(it.next());
+                result[i] = new AbstractMap.SimpleEntry<>(it.next());
             return result;
         }
 
@@ -1146,7 +1146,7 @@
                     .newInstance(a.getClass().getComponentType(), size);
             Iterator<Map.Entry<K,V>> it = iterator();
             for (int i = 0; i < size; i++)
-                a[i] = (T) new AbstractMap.SimpleEntry<K,V>(it.next());
+                a[i] = (T) new AbstractMap.SimpleEntry<>(it.next());
             if (a.length > size)
                 a[size] = null;
             return a;
diff --git a/src/share/classes/java/util/JumboEnumSet.java b/src/share/classes/java/util/JumboEnumSet.java
index aa61117..e325596 100644
--- a/src/share/classes/java/util/JumboEnumSet.java
+++ b/src/share/classes/java/util/JumboEnumSet.java
@@ -89,7 +89,7 @@
      * @return an iterator over the elements contained in this set
      */
     public Iterator<E> iterator() {
-        return new EnumSetIterator<E>();
+        return new EnumSetIterator<>();
     }
 
     private class EnumSetIterator<E extends Enum<E>> implements Iterator<E> {
diff --git a/src/share/classes/java/util/LinkedHashMap.java b/src/share/classes/java/util/LinkedHashMap.java
index 31e2a52..1beacef 100644
--- a/src/share/classes/java/util/LinkedHashMap.java
+++ b/src/share/classes/java/util/LinkedHashMap.java
@@ -237,7 +237,7 @@
      * the chain.
      */
     void init() {
-        header = new Entry<K,V>(-1, null, null, null);
+        header = new Entry<>(-1, null, null, null);
         header.before = header.after = header;
     }
 
@@ -438,7 +438,7 @@
      */
     void createEntry(int hash, K key, V value, int bucketIndex) {
         HashMap.Entry<K,V> old = table[bucketIndex];
-        Entry<K,V> e = new Entry<K,V>(hash, key, value, old);
+        Entry<K,V> e = new Entry<>(hash, key, value, old);
         table[bucketIndex] = e;
         e.addBefore(header);
         size++;
diff --git a/src/share/classes/java/util/LinkedList.java b/src/share/classes/java/util/LinkedList.java
index 6a473de..fbf8f5f 100644
--- a/src/share/classes/java/util/LinkedList.java
+++ b/src/share/classes/java/util/LinkedList.java
@@ -122,7 +122,7 @@
      */
     private void linkFirst(E e) {
         final Node<E> f = first;
-        final Node<E> newNode = new Node<E>(null, e, f);
+        final Node<E> newNode = new Node<>(null, e, f);
         first = newNode;
         if (f == null)
             last = newNode;
@@ -137,7 +137,7 @@
      */
     void linkLast(E e) {
         final Node<E> l = last;
-        final Node<E> newNode = new Node<E>(l, e, null);
+        final Node<E> newNode = new Node<>(l, e, null);
         last = newNode;
         if (l == null)
             first = newNode;
@@ -153,7 +153,7 @@
     void linkBefore(E e, Node<E> succ) {
         // assert succ != null;
         final Node<E> pred = succ.prev;
-        final Node<E> newNode = new Node<E>(pred, e, succ);
+        final Node<E> newNode = new Node<>(pred, e, succ);
         succ.prev = newNode;
         if (pred == null)
             first = newNode;
@@ -419,7 +419,7 @@
 
         for (Object o : a) {
             @SuppressWarnings("unchecked") E e = (E) o;
-            Node<E> newNode = new Node<E>(pred, e, null);
+            Node<E> newNode = new Node<>(pred, e, null);
             if (pred == null)
                 first = newNode;
             else
diff --git a/src/share/classes/java/util/ListResourceBundle.java b/src/share/classes/java/util/ListResourceBundle.java
index f35912f..736016f 100644
--- a/src/share/classes/java/util/ListResourceBundle.java
+++ b/src/share/classes/java/util/ListResourceBundle.java
@@ -187,7 +187,7 @@
             return;
 
         Object[][] contents = getContents();
-        HashMap<String,Object> temp = new HashMap<String,Object>(contents.length);
+        HashMap<String,Object> temp = new HashMap<>(contents.length);
         for (int i = 0; i < contents.length; ++i) {
             // key must be non-null String, value must be non-null
             String key = (String) contents[i][0];
diff --git a/src/share/classes/java/util/Locale.java b/src/share/classes/java/util/Locale.java
index ecaa9cc..1f0fbba 100644
--- a/src/share/classes/java/util/Locale.java
+++ b/src/share/classes/java/util/Locale.java
@@ -1449,10 +1449,15 @@
      * three-letter language abbreviation is not available for this locale.
      */
     public String getISO3Language() throws MissingResourceException {
-        String language3 = getISO3Code(_baseLocale.getLanguage(), LocaleISOData.isoLanguageTable);
+        String lang = _baseLocale.getLanguage();
+        if (lang.length() == 3) {
+            return lang;
+        }
+
+        String language3 = getISO3Code(lang, LocaleISOData.isoLanguageTable);
         if (language3 == null) {
             throw new MissingResourceException("Couldn't find 3-letter language code for "
-                    + _baseLocale.getLanguage(), "FormatData_" + toString(), "ShortLanguage");
+                    + lang, "FormatData_" + toString(), "ShortLanguage");
         }
         return language3;
     }
diff --git a/src/share/classes/java/util/PriorityQueue.java b/src/share/classes/java/util/PriorityQueue.java
index 5847b52..b4416ab 100644
--- a/src/share/classes/java/util/PriorityQueue.java
+++ b/src/share/classes/java/util/PriorityQueue.java
@@ -538,7 +538,7 @@
                     cursor--;
                 else {
                     if (forgetMeNot == null)
-                        forgetMeNot = new ArrayDeque<E>();
+                        forgetMeNot = new ArrayDeque<>();
                     forgetMeNot.add(moved);
                 }
             } else if (lastRetElt != null) {
diff --git a/src/share/classes/java/util/Properties.java b/src/share/classes/java/util/Properties.java
index d477553..47c9526 100644
--- a/src/share/classes/java/util/Properties.java
+++ b/src/share/classes/java/util/Properties.java
@@ -1011,7 +1011,7 @@
      * @since   1.6
      */
     public Set<String> stringPropertyNames() {
-        Hashtable<String, String> h = new Hashtable<String, String>();
+        Hashtable<String, String> h = new Hashtable<>();
         enumerateStringProperties(h);
         return h.keySet();
     }
diff --git a/src/share/classes/java/util/RegularEnumSet.java b/src/share/classes/java/util/RegularEnumSet.java
index e5afa32..c4f6215 100644
--- a/src/share/classes/java/util/RegularEnumSet.java
+++ b/src/share/classes/java/util/RegularEnumSet.java
@@ -71,7 +71,7 @@
      * @return an iterator over the elements contained in this set
      */
     public Iterator<E> iterator() {
-        return new EnumSetIterator<E>();
+        return new EnumSetIterator<>();
     }
 
     private class EnumSetIterator<E extends Enum<E>> implements Iterator<E> {
diff --git a/src/share/classes/java/util/ServiceLoader.java b/src/share/classes/java/util/ServiceLoader.java
index 46631c9..122b237 100644
--- a/src/share/classes/java/util/ServiceLoader.java
+++ b/src/share/classes/java/util/ServiceLoader.java
@@ -191,7 +191,7 @@
     private ClassLoader loader;
 
     // Cached providers, in instantiation order
-    private LinkedHashMap<String,S> providers = new LinkedHashMap<String,S>();
+    private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
 
     // The current lazy-lookup iterator
     private LazyIterator lookupIterator;
@@ -291,7 +291,7 @@
     {
         InputStream in = null;
         BufferedReader r = null;
-        ArrayList<String> names = new ArrayList<String>();
+        ArrayList<String> names = new ArrayList<>();
         try {
             in = u.openStream();
             r = new BufferedReader(new InputStreamReader(in, "utf-8"));
@@ -463,7 +463,7 @@
     public static <S> ServiceLoader<S> load(Class<S> service,
                                             ClassLoader loader)
     {
-        return new ServiceLoader<S>(service, loader);
+        return new ServiceLoader<>(service, loader);
     }
 
     /**
diff --git a/src/share/classes/java/util/TimSort.java b/src/share/classes/java/util/TimSort.java
index 6d4727a..f55a6b2 100644
--- a/src/share/classes/java/util/TimSort.java
+++ b/src/share/classes/java/util/TimSort.java
@@ -196,7 +196,7 @@
          * extending short natural runs to minRun elements, and merging runs
          * to maintain stack invariant.
          */
-        TimSort<T> ts = new TimSort<T>(a, c);
+        TimSort<T> ts = new TimSort<>(a, c);
         int minRun = minRunLength(nRemaining);
         do {
             // Identify next run
diff --git a/src/share/classes/java/util/TreeMap.java b/src/share/classes/java/util/TreeMap.java
index 727e70a..e256240 100644
--- a/src/share/classes/java/util/TreeMap.java
+++ b/src/share/classes/java/util/TreeMap.java
@@ -533,7 +533,7 @@
             // throw NullPointerException
             //
             // compare(key, key); // type check
-            root = new Entry<K,V>(key, value, null);
+            root = new Entry<>(key, value, null);
             size = 1;
             modCount++;
             return null;
@@ -569,7 +569,7 @@
                     return t.setValue(value);
             } while (t != null);
         }
-        Entry<K,V> e = new Entry<K,V>(key, value, parent);
+        Entry<K,V> e = new Entry<>(key, value, parent);
         if (cmp < 0)
             parent.left = e;
         else
@@ -1069,14 +1069,14 @@
         }
         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
                                       E toElement,   boolean toInclusive) {
-            return new KeySet<E>(m.subMap(fromElement, fromInclusive,
+            return new KeySet<>(m.subMap(fromElement, fromInclusive,
                                           toElement,   toInclusive));
         }
         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
-            return new KeySet<E>(m.headMap(toElement, inclusive));
+            return new KeySet<>(m.headMap(toElement, inclusive));
         }
         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
-            return new KeySet<E>(m.tailMap(fromElement, inclusive));
+            return new KeySet<>(m.tailMap(fromElement, inclusive));
         }
         public SortedSet<E> subSet(E fromElement, E toElement) {
             return subSet(fromElement, true, toElement, false);
@@ -1205,7 +1205,7 @@
      */
     static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
         return (e == null) ? null :
-            new AbstractMap.SimpleImmutableEntry<K,V>(e);
+            new AbstractMap.SimpleImmutableEntry<>(e);
     }
 
     /**
@@ -2406,7 +2406,7 @@
             value = (defaultVal != null ? defaultVal : (V) str.readObject());
         }
 
-        Entry<K,V> middle =  new Entry<K,V>(key, value, null);
+        Entry<K,V> middle =  new Entry<>(key, value, null);
 
         // color nodes in non-full bottommost level red
         if (level == redLevel)
diff --git a/src/share/classes/java/util/TreeSet.java b/src/share/classes/java/util/TreeSet.java
index 7164b5d..3eee2a8 100644
--- a/src/share/classes/java/util/TreeSet.java
+++ b/src/share/classes/java/util/TreeSet.java
@@ -138,7 +138,7 @@
      *        ordering} of the elements will be used.
      */
     public TreeSet(Comparator<? super E> comparator) {
-        this(new TreeMap<E,Object>(comparator));
+        this(new TreeMap<>(comparator));
     }
 
     /**
@@ -195,7 +195,7 @@
      * @since 1.6
      */
     public NavigableSet<E> descendingSet() {
-        return new TreeSet<E>(m.descendingMap());
+        return new TreeSet<>(m.descendingMap());
     }
 
     /**
@@ -322,7 +322,7 @@
      */
     public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
                                   E toElement,   boolean toInclusive) {
-        return new TreeSet<E>(m.subMap(fromElement, fromInclusive,
+        return new TreeSet<>(m.subMap(fromElement, fromInclusive,
                                        toElement,   toInclusive));
     }
 
@@ -335,7 +335,7 @@
      * @since 1.6
      */
     public NavigableSet<E> headSet(E toElement, boolean inclusive) {
-        return new TreeSet<E>(m.headMap(toElement, inclusive));
+        return new TreeSet<>(m.headMap(toElement, inclusive));
     }
 
     /**
@@ -347,7 +347,7 @@
      * @since 1.6
      */
     public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
-        return new TreeSet<E>(m.tailMap(fromElement, inclusive));
+        return new TreeSet<>(m.tailMap(fromElement, inclusive));
     }
 
     /**
@@ -477,7 +477,7 @@
             throw new InternalError();
         }
 
-        clone.m = new TreeMap<E,Object>(m);
+        clone.m = new TreeMap<>(m);
         return clone;
     }
 
@@ -524,9 +524,9 @@
         // Create backing TreeMap
         TreeMap<E,Object> tm;
         if (c==null)
-            tm = new TreeMap<E,Object>();
+            tm = new TreeMap<>();
         else
-            tm = new TreeMap<E,Object>(c);
+            tm = new TreeMap<>(c);
         m = tm;
 
         // Read in size
diff --git a/src/share/classes/java/util/WeakHashMap.java b/src/share/classes/java/util/WeakHashMap.java
index 44e541d..9a292f3 100644
--- a/src/share/classes/java/util/WeakHashMap.java
+++ b/src/share/classes/java/util/WeakHashMap.java
@@ -171,7 +171,7 @@
     /**
      * Reference queue for cleared WeakEntries
      */
-    private final ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
+    private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
 
     /**
      * The number of times this WeakHashMap has been structurally modified.
@@ -439,7 +439,7 @@
 
         modCount++;
         Entry<K,V> e = tab[i];
-        tab[i] = new Entry<K,V>(k, value, queue, h, e);
+        tab[i] = new Entry<>(k, value, queue, h, e);
         if (++size >= threshold)
             resize(tab.length * 2);
         return null;
@@ -955,10 +955,9 @@
         }
 
         private List<Map.Entry<K,V>> deepCopy() {
-            List<Map.Entry<K,V>> list =
-                new ArrayList<Map.Entry<K,V>>(size());
+            List<Map.Entry<K,V>> list = new ArrayList<>(size());
             for (Map.Entry<K,V> e : this)
-                list.add(new AbstractMap.SimpleEntry<K,V>(e));
+                list.add(new AbstractMap.SimpleEntry<>(e));
             return list;
         }
 
diff --git a/src/share/classes/java/util/jar/Pack200.java b/src/share/classes/java/util/jar/Pack200.java
index 8bf0f4e..feefc2b 100644
--- a/src/share/classes/java/util/jar/Pack200.java
+++ b/src/share/classes/java/util/jar/Pack200.java
@@ -732,14 +732,14 @@
     private synchronized static Object newInstance(String prop) {
         String implName = "(unknown)";
         try {
-            Class impl = (prop == PACK_PROVIDER)? packerImpl: unpackerImpl;
+            Class impl = (PACK_PROVIDER.equals(prop))? packerImpl: unpackerImpl;
             if (impl == null) {
                 // The first time, we must decide which class to use.
                 implName = java.security.AccessController.doPrivileged(
                     new sun.security.action.GetPropertyAction(prop,""));
                 if (implName != null && !implName.equals(""))
                     impl = Class.forName(implName);
-                else if (prop == PACK_PROVIDER)
+                else if (PACK_PROVIDER.equals(prop))
                     impl = com.sun.java.util.jar.pack.PackerImpl.class;
                 else
                     impl = com.sun.java.util.jar.pack.UnpackerImpl.class;
diff --git a/src/share/classes/java/util/logging/FileHandler.java b/src/share/classes/java/util/logging/FileHandler.java
index aff22b1..9566776 100644
--- a/src/share/classes/java/util/logging/FileHandler.java
+++ b/src/share/classes/java/util/logging/FileHandler.java
@@ -127,7 +127,7 @@
     private FileOutputStream lockStream;
     private File files[];
     private static final int MAX_LOCKS = 100;
-    private static java.util.HashMap<String, String> locks = new java.util.HashMap<String, String>();
+    private static java.util.HashMap<String, String> locks = new java.util.HashMap<>();
 
     // A metered stream is a subclass of OutputStream that
     //   (a) forwards all its output to a target stream
diff --git a/src/share/classes/java/util/logging/Level.java b/src/share/classes/java/util/logging/Level.java
index b7ab2f0..1b24daa 100644
--- a/src/share/classes/java/util/logging/Level.java
+++ b/src/share/classes/java/util/logging/Level.java
@@ -59,7 +59,7 @@
  */
 
 public class Level implements java.io.Serializable {
-    private static java.util.ArrayList<Level> known = new java.util.ArrayList<Level>();
+    private static java.util.ArrayList<Level> known = new java.util.ArrayList<>();
     private static String defaultBundle = "sun.util.logging.resources.logging";
 
     /**
diff --git a/src/share/classes/java/util/logging/LogManager.java b/src/share/classes/java/util/logging/LogManager.java
index ed577bf..fb07472 100644
--- a/src/share/classes/java/util/logging/LogManager.java
+++ b/src/share/classes/java/util/logging/LogManager.java
@@ -156,8 +156,7 @@
     private final static Level defaultLevel = Level.INFO;
 
     // Table of named Loggers that maps names to Loggers.
-    private Hashtable<String,LoggerWeakRef> namedLoggers =
-        new Hashtable<String,LoggerWeakRef>();
+    private Hashtable<String,LoggerWeakRef> namedLoggers = new Hashtable<>();
     // Tree of named Loggers
     private LogNode root = new LogNode(null);
     private Logger rootLogger;
@@ -422,7 +421,7 @@
     // loggerRefQueue holds LoggerWeakRef objects for Logger objects
     // that have been GC'ed.
     private final ReferenceQueue<Logger> loggerRefQueue
-        = new ReferenceQueue<Logger>();
+        = new ReferenceQueue<>();
 
     // Package-level inner class.
     // Helper class for managing WeakReferences to Logger objects.
@@ -672,7 +671,7 @@
                 name = "";
             }
             if (node.children == null) {
-                node.children = new HashMap<String,LogNode>();
+                node.children = new HashMap<>();
             }
             LogNode child = node.children.get(head);
             if (child == null) {
@@ -856,7 +855,7 @@
         }
         hands = hands.trim();
         int ix = 0;
-        Vector<String> result = new Vector<String>();
+        Vector<String> result = new Vector<>();
         while (ix < hands.length()) {
             int end = ix;
             while (end < hands.length()) {
diff --git a/src/share/classes/java/util/logging/LogRecord.java b/src/share/classes/java/util/logging/LogRecord.java
index 09a4f50..93540d9 100644
--- a/src/share/classes/java/util/logging/LogRecord.java
+++ b/src/share/classes/java/util/logging/LogRecord.java
@@ -85,8 +85,7 @@
     private static final AtomicInteger nextThreadId
         = new AtomicInteger(MIN_SEQUENTIAL_THREAD_ID);
 
-    private static final ThreadLocal<Integer> threadIds
-        = new ThreadLocal<Integer>();
+    private static final ThreadLocal<Integer> threadIds = new ThreadLocal<>();
 
     /**
      * @serial Logging message level
diff --git a/src/share/classes/java/util/logging/Logger.java b/src/share/classes/java/util/logging/Logger.java
index 72aade9..4d822de 100644
--- a/src/share/classes/java/util/logging/Logger.java
+++ b/src/share/classes/java/util/logging/Logger.java
@@ -170,7 +170,7 @@
     private LogManager manager;
     private String name;
     private final CopyOnWriteArrayList<Handler> handlers =
-        new CopyOnWriteArrayList<Handler>();
+        new CopyOnWriteArrayList<>();
     private String resourceBundleName;
     private volatile boolean useParentHandlers = true;
     private volatile Filter filter;
@@ -1420,13 +1420,13 @@
             // Set our new parent.
             parent = newParent;
             if (parent.kids == null) {
-                parent.kids = new ArrayList<LogManager.LoggerWeakRef>(2);
+                parent.kids = new ArrayList<>(2);
             }
             if (ref == null) {
                 // we didn't have a previous parent
                 ref = manager.new LoggerWeakRef(this);
             }
-            ref.setParentRef(new WeakReference<Logger>(parent));
+            ref.setParentRef(new WeakReference<>(parent));
             parent.kids.add(ref);
 
             // As a result of the reparenting, the effective level
diff --git a/src/share/classes/java/util/logging/Logging.java b/src/share/classes/java/util/logging/Logging.java
index d8866e8..94a52f9 100644
--- a/src/share/classes/java/util/logging/Logging.java
+++ b/src/share/classes/java/util/logging/Logging.java
@@ -56,7 +56,7 @@
 
     public List<String> getLoggerNames() {
         Enumeration loggers = logManager.getLoggerNames();
-        ArrayList<String> array = new ArrayList<String>();
+        ArrayList<String> array = new ArrayList<>();
 
         for (; loggers.hasMoreElements();) {
             array.add((String) loggers.nextElement());
diff --git a/src/share/classes/java/util/prefs/AbstractPreferences.java b/src/share/classes/java/util/prefs/AbstractPreferences.java
index 0624372..249adcf 100644
--- a/src/share/classes/java/util/prefs/AbstractPreferences.java
+++ b/src/share/classes/java/util/prefs/AbstractPreferences.java
@@ -155,8 +155,7 @@
      * All known unremoved children of this node.  (This "cache" is consulted
      * prior to calling childSpi() or getChild().
      */
-    private Map<String, AbstractPreferences> kidCache
-        = new HashMap<String, AbstractPreferences>();
+    private Map<String, AbstractPreferences> kidCache = new HashMap<>();
 
     /**
      * This field is used to keep track of whether or not this node has
@@ -713,7 +712,7 @@
             if (removed)
                 throw new IllegalStateException("Node has been removed.");
 
-            Set<String> s = new TreeSet<String>(kidCache.keySet());
+            Set<String> s = new TreeSet<>(kidCache.keySet());
             for (String kid : childrenNamesSpi())
                 s.add(kid);
             return s.toArray(EMPTY_STRING_ARRAY);
@@ -1442,8 +1441,7 @@
      * event delivery from preference activity, greatly simplifying
      * locking and reducing opportunity for deadlock.
      */
-    private static final List<EventObject> eventQueue
-        = new LinkedList<EventObject>();
+    private static final List<EventObject> eventQueue = new LinkedList<>();
 
     /**
      * These two classes are used to distinguish NodeChangeEvents on
diff --git a/src/share/classes/java/util/regex/Pattern.java b/src/share/classes/java/util/regex/Pattern.java
index f98e024..7c012e5 100644
--- a/src/share/classes/java/util/regex/Pattern.java
+++ b/src/share/classes/java/util/regex/Pattern.java
@@ -1068,7 +1068,7 @@
     public String[] split(CharSequence input, int limit) {
         int index = 0;
         boolean matchLimited = limit > 0;
-        ArrayList<String> matchList = new ArrayList<String>();
+        ArrayList<String> matchList = new ArrayList<>();
         Matcher m = matcher(input);
 
         // Add segments before each match found
@@ -1566,7 +1566,7 @@
 
     Map<String, Integer> namedGroups() {
         if (namedGroups == null)
-            namedGroups = new HashMap<String, Integer>(2);
+            namedGroups = new HashMap<>(2);
         return namedGroups;
     }
 
@@ -5309,7 +5309,7 @@
         }
 
         private static final HashMap<String, CharPropertyFactory> map
-            = new HashMap<String, CharPropertyFactory>();
+            = new HashMap<>();
 
         static {
             // Unicode character property aliases, defined in
diff --git a/src/share/classes/java/util/zip/Inflater.java b/src/share/classes/java/util/zip/Inflater.java
index c37ce5e..1b1456e 100644
--- a/src/share/classes/java/util/zip/Inflater.java
+++ b/src/share/classes/java/util/zip/Inflater.java
@@ -382,6 +382,12 @@
             throw new NullPointerException("Inflater has been closed");
     }
 
+    boolean ended() {
+        synchronized (zsRef) {
+            return zsRef.address() == 0;
+        }
+    }
+
     private native static void initIDs();
     private native static long init(boolean nowrap);
     private native static void setDictionary(long addr, byte[] b, int off,
diff --git a/src/share/classes/java/util/zip/ZipFile.java b/src/share/classes/java/util/zip/ZipFile.java
index 98da2c8..911ec46 100644
--- a/src/share/classes/java/util/zip/ZipFile.java
+++ b/src/share/classes/java/util/zip/ZipFile.java
@@ -424,6 +424,8 @@
      */
     private void releaseInflater(Inflater inf) {
         synchronized (inflaters) {
+            if (inf.ended())
+                return;
             inf.reset();
             inflaters.add(inf);
         }
@@ -543,7 +545,7 @@
 
             if (streams.size() !=0) {
                 Set<InputStream> copy = streams;
-                streams = new HashSet<InputStream>();
+                streams = new HashSet<>();
                 for (InputStream is: copy)
                     is.close();
             }
diff --git a/src/share/classes/java/util/zip/ZipOutputStream.java b/src/share/classes/java/util/zip/ZipOutputStream.java
index 1e94195..62cbd26 100644
--- a/src/share/classes/java/util/zip/ZipOutputStream.java
+++ b/src/share/classes/java/util/zip/ZipOutputStream.java
@@ -52,8 +52,8 @@
     }
 
     private XEntry current;
-    private Vector<XEntry> xentries = new Vector<XEntry>();
-    private HashSet<String> names = new HashSet<String>();
+    private Vector<XEntry> xentries = new Vector<>();
+    private HashSet<String> names = new HashSet<>();
     private CRC32 crc = new CRC32();
     private long written = 0;
     private long locoff = 0;
diff --git a/src/share/classes/javax/net/ssl/X509ExtendedTrustManager.java b/src/share/classes/javax/net/ssl/X509ExtendedTrustManager.java
index e69a282..f14489f 100644
--- a/src/share/classes/javax/net/ssl/X509ExtendedTrustManager.java
+++ b/src/share/classes/javax/net/ssl/X509ExtendedTrustManager.java
@@ -63,7 +63,7 @@
      * should be "RSA". Checking is case-sensitive.
      * <p>
      * If the <code>socket</code> parameter is an instance of
-     * {@link javax.net.SSLSocket}, and the endpoint identification
+     * {@link javax.net.ssl.SSLSocket}, and the endpoint identification
      * algorithm of the <code>SSLParameters</code> is non-empty, to prevent
      * man-in-the-middle attacks, the address that the <code>socket</code>
      * connected to should be checked against the peer's identity presented
@@ -71,7 +71,7 @@
      * identification algorithm.
      * <p>
      * If the <code>socket</code> parameter is an instance of
-     * {@link javax.net.SSLSocket}, and the algorithm constraints of the
+     * {@link javax.net.ssl.SSLSocket}, and the algorithm constraints of the
      * <code>SSLParameters</code> is non-null, for every certificate in the
      * certification path, fields such as subject public key, the signature
      * algorithm, key usage, extended key usage, etc. need to conform to the
@@ -88,8 +88,8 @@
      * @throws CertificateException if the certificate chain is not trusted
      *        by this TrustManager
      *
-     * @see SSLParameters#getEndpointIdentificationProtocol
-     * @see SSLParameters#setEndpointIdentificationProtocol(String)
+     * @see SSLParameters#getEndpointIdentificationAlgorithm
+     * @see SSLParameters#setEndpointIdentificationAlgorithm(String)
      * @see SSLParameters#getAlgorithmConstraints
      * @see SSLParameters#setAlgorithmConstraints(AlgorithmConstraints)
      */
@@ -111,7 +111,7 @@
      * certificate is used. Checking is case-sensitive.
      * <p>
      * If the <code>socket</code> parameter is an instance of
-     * {@link javax.net.SSLSocket}, and the endpoint identification
+     * {@link javax.net.ssl.SSLSocket}, and the endpoint identification
      * algorithm of the <code>SSLParameters</code> is non-empty, to prevent
      * man-in-the-middle attacks, the address that the <code>socket</code>
      * connected to should be checked against the peer's identity presented
@@ -119,7 +119,7 @@
      * identification algorithm.
      * <p>
      * If the <code>socket</code> parameter is an instance of
-     * {@link javax.net.SSLSocket}, and the algorithm constraints of the
+     * {@link javax.net.ssl.SSLSocket}, and the algorithm constraints of the
      *  <code>SSLParameters</code> is non-null, for every certificate in the
      * certification path, fields such as subject public key, the signature
      * algorithm, key usage, extended key usage, etc. need to conform to the
@@ -136,8 +136,8 @@
      * @throws CertificateException if the certificate chain is not trusted
      *        by this TrustManager
      *
-     * @see SSLParameters#getEndpointIdentificationProtocol
-     * @see SSLParameters#setEndpointIdentificationProtocol(String)
+     * @see SSLParameters#getEndpointIdentificationAlgorithm
+     * @see SSLParameters#setEndpointIdentificationAlgorithm(String)
      * @see SSLParameters#getAlgorithmConstraints
      * @see SSLParameters#setAlgorithmConstraints(AlgorithmConstraints)
      */
@@ -177,8 +177,8 @@
      * @throws CertificateException if the certificate chain is not trusted
      *        by this TrustManager
      *
-     * @see SSLParameters#getEndpointIdentificationProtocol
-     * @see SSLParameters#setEndpointIdentificationProtocol(String)
+     * @see SSLParameters#getEndpointIdentificationAlgorithm
+     * @see SSLParameters#setEndpointIdentificationAlgorithm(String)
      * @see SSLParameters#getAlgorithmConstraints
      * @see SSLParameters#setAlgorithmConstraints(AlgorithmConstraints)
      */
@@ -223,8 +223,8 @@
      * @throws CertificateException if the certificate chain is not trusted
      *        by this TrustManager
      *
-     * @see SSLParameters#getEndpointIdentificationProtocol
-     * @see SSLParameters#setEndpointIdentificationProtocol(String)
+     * @see SSLParameters#getEndpointIdentificationAlgorithm
+     * @see SSLParameters#setEndpointIdentificationAlgorithm(String)
      * @see SSLParameters#getAlgorithmConstraints
      * @see SSLParameters#setAlgorithmConstraints(AlgorithmConstraints)
      */
diff --git a/src/share/classes/javax/sound/midi/MidiSystem.java b/src/share/classes/javax/sound/midi/MidiSystem.java
index d3ce81e..b2a47dc 100644
--- a/src/share/classes/javax/sound/midi/MidiSystem.java
+++ b/src/share/classes/javax/sound/midi/MidiSystem.java
@@ -310,7 +310,7 @@
         } else {
             transmitter = device.getTransmitter();
         }
-        if (!(transmitter instanceof MidiDeviceReceiver)) {
+        if (!(transmitter instanceof MidiDeviceTransmitter)) {
             transmitter = new MidiDeviceTransmitterEnvelope(device, transmitter);
         }
         return transmitter;
diff --git a/src/share/classes/javax/swing/JSlider.java b/src/share/classes/javax/swing/JSlider.java
index 156b9e4..8d188b9 100644
--- a/src/share/classes/javax/swing/JSlider.java
+++ b/src/share/classes/javax/swing/JSlider.java
@@ -40,7 +40,8 @@
 
 /**
  * A component that lets the user graphically select a value by sliding
- * a knob within a bounded interval.
+ * a knob within a bounded interval. The knob is always positioned
+ * at the points that match integer values within the specified interval.
  * <p>
  * The slider can show both
  * major tick marks, and minor tick marks between the major ones.  The number of
diff --git a/src/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java b/src/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java
index b26f226..a57638e 100644
--- a/src/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java
+++ b/src/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java
@@ -908,6 +908,14 @@
             int height = parent.getHeight();
 
             Insets insets = parent.getInsets();
+
+            if (nextButton == null && previousButton == null) {
+                setBounds(editor, insets.left,  insets.top, width - insets.left - insets.right,
+                        height - insets.top - insets.bottom);
+
+                return;
+            }
+
             Dimension nextD = preferredSize(nextButton);
             Dimension previousD = preferredSize(previousButton);
             int buttonsWidth = Math.max(nextD.width, previousD.width);
diff --git a/src/share/classes/sun/awt/FontConfiguration.java b/src/share/classes/sun/awt/FontConfiguration.java
index a2593cc..ba8f6e5 100644
--- a/src/share/classes/sun/awt/FontConfiguration.java
+++ b/src/share/classes/sun/awt/FontConfiguration.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 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
@@ -37,10 +37,10 @@
 import java.nio.charset.CharsetEncoder;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import java.util.Arrays;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Hashtable;
-import java.util.Iterator;
 import java.util.Locale;
 import java.util.Map.Entry;
 import java.util.Properties;
@@ -329,6 +329,8 @@
      * tables.
      */
     public static void saveBinary(OutputStream out) throws IOException {
+        sanityCheck();
+
         DataOutputStream dataOut = new DataOutputStream(out);
         writeShortTable(dataOut, head);
         writeShortTable(dataOut, table_scriptIDs);
@@ -350,7 +352,6 @@
         if (verbose) {
             dump();
         }
-        sanityCheck();
     }
 
     //private static boolean loadingProperties;
@@ -1343,6 +1344,11 @@
     private static short[] table_stringIDs;
     private static char[]  table_stringTable;
 
+    /**
+     * Checks consistencies of complied fontconfig data. This method
+     * is called only at the build-time from
+     * build.tools.compilefontconfig.CompileFontConfig.
+     */
     private static void sanityCheck() {
         int errors = 0;
 
@@ -1358,12 +1364,20 @@
         //componentFontNameID starts from "1"
         for (int ii = 1; ii < table_filenames.length; ii++) {
             if (table_filenames[ii] == -1) {
-                System.out.println("\n Warning: "
-                                   + "<filename."
-                                   + getString(table_componentFontNameIDs[ii])
-                                   + "> entry is missing!!!");
-                if (!osName.contains("Linux")) {
+                // The corresponding finename entry for a component
+                // font name is mandatory on Windows, but it's
+                // optional on Solaris and Linux.
+                if (osName.contains("Windows")) {
+                    System.err.println("\n Error: <filename."
+                                       + getString(table_componentFontNameIDs[ii])
+                                       + "> entry is missing!!!");
                     errors++;
+                } else {
+                    if (verbose && !isEmpty(table_filenames)) {
+                        System.err.println("\n Note: 'filename' entry is undefined for \""
+                                           + getString(table_componentFontNameIDs[ii])
+                                           + "\"");
+                    }
                 }
             }
         }
@@ -1382,7 +1396,7 @@
                         int jj = iii * NUM_STYLES + iij;
                         short ffid = table_scriptFonts[fid + jj];
                         if (ffid == 0) {
-                            System.out.println("\n Error: <"
+                            System.err.println("\n Error: <"
                                            + getFontName(iii) + "."
                                            + getStyleName(iij) + "."
                                            + getString(table_scriptIDs[ii])
@@ -1402,7 +1416,7 @@
                         script.contains("symbol")) {
                         continue;
                     }
-                    System.out.println("\nError: "
+                    System.err.println("\nError: "
                                        + "<awtfontpath."
                                        + script
                                        + "> entry is missing!!!");
@@ -1411,13 +1425,21 @@
             }
         }
         if (errors != 0) {
-            System.out.println("!!THERE ARE " + errors + " ERROR(S) IN "
+            System.err.println("!!THERE ARE " + errors + " ERROR(S) IN "
                                + "THE FONTCONFIG FILE, PLEASE CHECK ITS CONTENT!!\n");
             System.exit(1);
-
         }
     }
 
+    private static boolean isEmpty(short[] a) {
+        for (short s : a) {
+            if (s != -1) {
+                return false;
+            }
+        }
+        return true;
+    }
+
     //dump the fontconfig data tables
     private static void dump() {
         System.out.println("\n----Head Table------------");
@@ -1652,20 +1674,16 @@
 
     private static void writeShortTable(DataOutputStream out, short[] data)
         throws IOException {
-        for (int i = 0; i < data.length; i++) {
-            out.writeShort(data[i]);
+        for (short val : data) {
+            out.writeShort(val);
         }
     }
 
-    private static short[] toList(HashMap map) {
+    private static short[] toList(HashMap<String, Short> map) {
         short[] list = new short[map.size()];
-        for (int i = 0; i < list.length; i++) {
-            list[i] = -1;
-        }
-        Iterator iterator = map.entrySet().iterator();
-        while (iterator.hasNext()) {
-            Entry<String, Short> entry = (Entry <String, Short>)iterator.next();
-            list[entry.getValue().shortValue()] = getStringID(entry.getKey());
+        Arrays.fill(list, (short) -1);
+        for (Entry<String, Short> entry : map.entrySet()) {
+            list[entry.getValue()] = getStringID(entry.getKey());
         }
         return list;
     }
@@ -1763,25 +1781,19 @@
             int len = table_scriptIDs.length + scriptFonts.size() * 20;
             table_scriptFonts = new short[len];
 
-            Iterator iterator = scriptAllfonts.entrySet().iterator();
-            while (iterator.hasNext()) {
-                Entry<Short, Short> entry = (Entry <Short, Short>)iterator.next();
-                table_scriptFonts[entry.getKey().intValue()] = (short)entry.getValue().shortValue();
+            for (Entry<Short, Short> entry : scriptAllfonts.entrySet()) {
+                table_scriptFonts[entry.getKey().intValue()] = entry.getValue();
             }
             int off = table_scriptIDs.length;
-            iterator = scriptFonts.entrySet().iterator();
-            while (iterator.hasNext()) {
-                Entry<Short, Short[]> entry = (Entry <Short, Short[]>)iterator.next();
+            for (Entry<Short, Short[]> entry : scriptFonts.entrySet()) {
                 table_scriptFonts[entry.getKey().intValue()] = (short)-off;
                 Short[] v = entry.getValue();
-                int i = 0;
-                while (i < 20) {
+                for (int i = 0; i < 20; i++) {
                     if (v[i] != null) {
-                        table_scriptFonts[off++] = v[i].shortValue();
+                        table_scriptFonts[off++] = v[i];
                     } else {
                         table_scriptFonts[off++] = 0;
                     }
-                    i++;
                 }
             }
 
@@ -1792,9 +1804,7 @@
             //(3) sequences  elcID -> XXXX[1|5] -> scriptID[]
             head[INDEX_sequences] = (short)(head[INDEX_elcIDs]  + table_elcIDs.length);
             table_sequences = new short[elcIDs.size() * NUM_FONTS];
-            iterator = sequences.entrySet().iterator();
-            while (iterator.hasNext()) {
-                Entry<Short, short[]> entry = (Entry <Short, short[]>)iterator.next();
+            for (Entry<Short, short[]> entry : sequences.entrySet()) {
                 //table_sequences[entry.getKey().intValue()] = (short)-off;
                 int k = entry.getKey().intValue();
                 short[] v = entry.getValue();
@@ -1827,31 +1837,24 @@
             //(6)componentFontNameID -> filenameID
             head[INDEX_filenames] = (short)(head[INDEX_componentFontNameIDs]  + table_componentFontNameIDs.length);
             table_filenames = new short[table_componentFontNameIDs.length];
-            for (int i = 0; i < table_filenames.length; i++) {
-                table_filenames[i] = -1;
-            }
-            iterator = filenames.entrySet().iterator();
-            while (iterator.hasNext()) {
-                Entry<Short, Short> entry = (Entry <Short, Short>)iterator.next();
-                table_filenames[entry.getKey().shortValue()] = entry.getValue().shortValue();
+            Arrays.fill(table_filenames, (short) -1);
+
+            for (Entry<Short, Short> entry : filenames.entrySet()) {
+                table_filenames[entry.getKey()] = entry.getValue();
             }
 
             //(7)scriptID-> awtfontpath
             //the paths are stored as scriptID -> stringID in awtfontpahts
             head[INDEX_awtfontpaths] = (short)(head[INDEX_filenames]  + table_filenames.length);
             table_awtfontpaths = new short[table_scriptIDs.length];
-            iterator = awtfontpaths.entrySet().iterator();
-            while (iterator.hasNext()) {
-                Entry<Short, Short> entry = (Entry <Short, Short>)iterator.next();
-                table_awtfontpaths[entry.getKey().shortValue()] = entry.getValue().shortValue();
+            for (Entry<Short, Short> entry : awtfontpaths.entrySet()) {
+                table_awtfontpaths[entry.getKey()] = entry.getValue();
             }
 
             //(8)exclusions
             head[INDEX_exclusions] = (short)(head[INDEX_awtfontpaths]  + table_awtfontpaths.length);
             table_exclusions = new short[scriptIDs.size()];
-            iterator = exclusions.entrySet().iterator();
-            while (iterator.hasNext()) {
-                Entry<Short, int[]> entry = (Entry <Short, int[]>)iterator.next();
+            for (Entry<Short, int[]> entry : exclusions.entrySet()) {
                 int[] exI = entry.getValue();
                 char[] exC = new char[exI.length * 2];
                 int j = 0;
@@ -1859,17 +1862,15 @@
                     exC[j++] = (char) (exI[i] >> 16);
                     exC[j++] = (char) (exI[i] & 0xffff);
                 }
-                table_exclusions[entry.getKey().shortValue()] = getStringID(new String (exC));
+                table_exclusions[entry.getKey()] = getStringID(new String (exC));
             }
             //(9)proportionals
             head[INDEX_proportionals] = (short)(head[INDEX_exclusions]  + table_exclusions.length);
             table_proportionals = new short[proportionals.size() * 2];
-            iterator = proportionals.entrySet().iterator();
             int j = 0;
-            while (iterator.hasNext()) {
-                Entry<Short, Short> entry = (Entry <Short, Short>)iterator.next();
-                table_proportionals[j++] = entry.getKey().shortValue();
-                table_proportionals[j++] = entry.getValue().shortValue();
+            for (Entry<Short, Short> entry : proportionals.entrySet()) {
+                table_proportionals[j++] = entry.getKey();
+                table_proportionals[j++] = entry.getValue();
             }
 
             //(10) see (1) for info, the only difference is "xxx.motif"
@@ -1878,22 +1879,18 @@
                 len = table_scriptIDs.length + scriptFontsMotif.size() * 20;
                 table_scriptFontsMotif = new short[len];
 
-                iterator = scriptAllfontsMotif.entrySet().iterator();
-                while (iterator.hasNext()) {
-                    Entry<Short, Short> entry = (Entry <Short, Short>)iterator.next();
+                for (Entry<Short, Short> entry : scriptAllfontsMotif.entrySet()) {
                     table_scriptFontsMotif[entry.getKey().intValue()] =
-                      (short)entry.getValue().shortValue();
+                      (short)entry.getValue();
                 }
                 off = table_scriptIDs.length;
-                iterator = scriptFontsMotif.entrySet().iterator();
-                while (iterator.hasNext()) {
-                    Entry<Short, Short[]> entry = (Entry <Short, Short[]>)iterator.next();
+                for (Entry<Short, Short[]> entry : scriptFontsMotif.entrySet()) {
                     table_scriptFontsMotif[entry.getKey().intValue()] = (short)-off;
                     Short[] v = entry.getValue();
                     int i = 0;
                     while (i < 20) {
                         if (v[i] != null) {
-                            table_scriptFontsMotif[off++] = v[i].shortValue();
+                            table_scriptFontsMotif[off++] = v[i];
                         } else {
                             table_scriptFontsMotif[off++] = 0;
                         }
@@ -1907,12 +1904,10 @@
             //(11)short[] alphabeticSuffix
             head[INDEX_alphabeticSuffix] = (short)(head[INDEX_scriptFontsMotif] + table_scriptFontsMotif.length);
             table_alphabeticSuffix = new short[alphabeticSuffix.size() * 2];
-            iterator = alphabeticSuffix.entrySet().iterator();
             j = 0;
-            while (iterator.hasNext()) {
-                Entry<Short, Short> entry = (Entry <Short, Short>)iterator.next();
-                table_alphabeticSuffix[j++] = entry.getKey().shortValue();
-                table_alphabeticSuffix[j++] = entry.getValue().shortValue();
+            for (Entry<Short, Short> entry : alphabeticSuffix.entrySet()) {
+                table_alphabeticSuffix[j++] = entry.getKey();
+                table_alphabeticSuffix[j++] = entry.getValue();
             }
 
             //(15)short[] fallbackScriptIDs; just put the ID in head
diff --git a/src/share/classes/sun/awt/SunToolkit.java b/src/share/classes/sun/awt/SunToolkit.java
index 58ff286..0442aee 100644
--- a/src/share/classes/sun/awt/SunToolkit.java
+++ b/src/share/classes/sun/awt/SunToolkit.java
@@ -102,26 +102,6 @@
     public final static int MAX_BUTTONS_SUPPORTED = 20;
 
     public SunToolkit() {
-        /* If awt.threadgroup is set to class name the instance of
-         * this class is created (should be subclass of ThreadGroup)
-         * and EventDispatchThread is created inside of it
-         *
-         * If loaded class overrides uncaughtException instance
-         * handles all uncaught exception on EventDispatchThread
-         */
-        ThreadGroup threadGroup = null;
-        String tgName = System.getProperty("awt.threadgroup", "");
-
-        if (tgName.length() != 0) {
-            try {
-                Constructor ctor = Class.forName(tgName).
-                    getConstructor(new Class[] {String.class});
-                threadGroup = (ThreadGroup)ctor.newInstance(new Object[] {"AWT-ThreadGroup"});
-            } catch (Exception e) {
-                System.err.println("Failed loading " + tgName + ": " + e);
-            }
-        }
-
         Runnable initEQ = new Runnable() {
             public void run () {
                 EventQueue eventQueue;
@@ -144,17 +124,7 @@
             }
         };
 
-        if (threadGroup != null) {
-            Thread eqInitThread = new Thread(threadGroup, initEQ, "EventQueue-Init");
-            eqInitThread.start();
-            try {
-                eqInitThread.join();
-            } catch (InterruptedException e) {
-                e.printStackTrace();
-            }
-        } else {
-            initEQ.run();
-        }
+        initEQ.run();
     }
 
     public boolean useBufferPerWindow() {
diff --git a/src/share/classes/sun/io/Converters.java b/src/share/classes/sun/io/Converters.java
index 2c95300..d09bc1e 100644
--- a/src/share/classes/sun/io/Converters.java
+++ b/src/share/classes/sun/io/Converters.java
@@ -120,7 +120,7 @@
 
     private static Class<?> cache(int type, Object encoding, Class<?> c) {
         SoftReference<Object[]>[] srs = classCache[type];
-        srs[CACHE_SIZE - 1] = new SoftReference<Object[]>(new Object[] { c, encoding });
+        srs[CACHE_SIZE - 1] = new SoftReference<>(new Object[] { c, encoding });
         moveToFront(srs, CACHE_SIZE - 1);
         return c;
     }
diff --git a/src/share/classes/sun/launcher/LauncherHelper.java b/src/share/classes/sun/launcher/LauncherHelper.java
index dbaebc0..3ca01da 100644
--- a/src/share/classes/sun/launcher/LauncherHelper.java
+++ b/src/share/classes/sun/launcher/LauncherHelper.java
@@ -45,15 +45,18 @@
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.math.BigDecimal;
-import java.math.MathContext;
 import java.math.RoundingMode;
 import java.util.ResourceBundle;
 import java.text.MessageFormat;
 import java.util.ArrayList;
 import java.util.Collections;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Locale;
+import java.util.Locale.Category;
 import java.util.Properties;
+import java.util.Set;
+import java.util.TreeSet;
 import java.util.jar.Attributes;
 import java.util.jar.JarFile;
 import java.util.jar.Manifest;
@@ -73,11 +76,6 @@
     private static final String PROP_SETTINGS   = "Property settings:";
     private static final String LOCALE_SETTINGS = "Locale settings:";
 
-    private static final long K = 1024;
-    private static final long M = K * K;
-    private static final long G = M * K;
-    private static final long T = G * K;
-
     private static synchronized ResourceBundle getLauncherResourceBundle() {
         if (javarb == null) {
             javarb = ResourceBundle.getBundle(defaultBundleName);
@@ -96,14 +94,20 @@
      * optionFlag: specifies which options to print default is all other
      *    possible values are vm, properties, locale.
      *
+     * initialHeapSize: in bytes, as set by the launcher, a zero-value indicates
+     *    this code should determine this value, using a suitable method or
+     *    the line could be omitted.
+     *
      * maxHeapSize: in bytes, as set by the launcher, a zero-value indicates
      *    this code should determine this value, using a suitable method.
      *
      * stackSize: in bytes, as set by the launcher, a zero-value indicates
-     * this code determine this value, using a suitable method.
+     *    this code determine this value, using a suitable method or omit the
+     *    line entirely.
      */
     static void showSettings(boolean printToStderr, String optionFlag,
-            long maxHeapSize, long stackSize, boolean isServer) {
+            long initialHeapSize, long maxHeapSize, long stackSize,
+            boolean isServer) {
 
         PrintStream ostream = (printToStderr) ? System.err : System.out;
         String opts[] = optionFlag.split(":");
@@ -112,7 +116,8 @@
                 : "all";
         switch (optStr) {
             case "vm":
-                printVmSettings(ostream, maxHeapSize, stackSize, isServer);
+                printVmSettings(ostream, initialHeapSize, maxHeapSize,
+                        stackSize, isServer);
                 break;
             case "properties":
                 printProperties(ostream);
@@ -121,7 +126,8 @@
                 printLocale(ostream);
                 break;
             default:
-                printVmSettings(ostream, maxHeapSize, stackSize, isServer);
+                printVmSettings(ostream, initialHeapSize, maxHeapSize,
+                        stackSize, isServer);
                 printProperties(ostream);
                 printLocale(ostream);
                 break;
@@ -131,18 +137,25 @@
     /*
      * prints the main vm settings subopt/section
      */
-    private static void printVmSettings(PrintStream ostream, long maxHeapSize,
+    private static void printVmSettings(PrintStream ostream,
+            long initialHeapSize, long maxHeapSize,
             long stackSize, boolean isServer) {
 
         ostream.println(VM_SETTINGS);
         if (stackSize != 0L) {
-            ostream.println(INDENT + "Stack Size: " + scaleValue(stackSize));
+            ostream.println(INDENT + "Stack Size: " +
+                    SizePrefix.scaleValue(stackSize));
+        }
+        if (initialHeapSize != 0L) {
+             ostream.println(INDENT + "Min. Heap Size: " +
+                    SizePrefix.scaleValue(initialHeapSize));
         }
         if (maxHeapSize != 0L) {
-            ostream.println(INDENT + "Max. Heap Size: " + scaleValue(maxHeapSize));
+            ostream.println(INDENT + "Max. Heap Size: " +
+                    SizePrefix.scaleValue(maxHeapSize));
         } else {
             ostream.println(INDENT + "Max. Heap Size (Estimated): "
-                    + scaleValue(Runtime.getRuntime().maxMemory()));
+                    + SizePrefix.scaleValue(Runtime.getRuntime().maxMemory()));
         }
         ostream.println(INDENT + "Ergonomics Machine Class: "
                 + ((isServer) ? "server" : "client"));
@@ -152,28 +165,6 @@
     }
 
     /*
-     * scale the incoming values to a human readable form, represented as
-     * K, M, G and T, see java.c parse_size for the scaled values and
-     * suffixes.
-     */
-
-    private static String scaleValue(double v) {
-        MathContext mc2 = new MathContext(3, RoundingMode.HALF_EVEN);
-
-        if (v >= K && v < M) {
-            return (new BigDecimal(v / K, mc2)).toPlainString() + "K";
-        } else if (v >= M && v < G) {
-            return (new BigDecimal(v / M, mc2)).toPlainString() + "M";
-        } else if (v >= G && v < T) {
-            return (new BigDecimal(v / G, mc2)).toPlainString() + "G";
-        } else if (v >= T) {
-            return (new BigDecimal(v / T, mc2)).toPlainString() + "T";
-        } else {
-            return String.format("%.0f", v);
-        }
-    }
-
-    /*
      * prints the properties subopt/section
      */
     private static void printProperties(PrintStream ostream) {
@@ -196,16 +187,17 @@
             String key, String value) {
         ostream.print(INDENT + key + " = ");
         if (key.equals("line.separator")) {
-            byte[] bytes = value.getBytes();
-            for (byte b : bytes) {
+            for (byte b : value.getBytes()) {
                 switch (b) {
                     case 0xd:
-                        ostream.print("CR ");
+                        ostream.print("\\r ");
                         break;
                     case 0xa:
-                        ostream.print("LF ");
+                        ostream.print("\\n ");
                         break;
                     default:
+                        // print any bizzare line separators in hex, but really
+                        // shouldn't happen.
                         ostream.printf("0x%02X", b & 0xff);
                         break;
                 }
@@ -217,15 +209,14 @@
             ostream.println(value);
             return;
         }
-        // pretty print the path values as a list
         String[] values = value.split(System.getProperty("path.separator"));
-        int len = values.length;
-        for (int i = 0 ; i < len ; i++) {
-            if (i == 0) { // first line treated specially
-                ostream.println(values[i]);
+        boolean first = true;
+        for (String s : values) {
+            if (first) { // first line treated specially
+                ostream.println(s);
+                first = false;
             } else { // following lines prefix with indents
-                ostream.print(INDENT + INDENT);
-                ostream.println(values[i]);
+                ostream.println(INDENT + INDENT + s);
             }
         }
     }
@@ -236,21 +227,35 @@
     private static void printLocale(PrintStream ostream) {
         Locale locale = Locale.getDefault();
         ostream.println(LOCALE_SETTINGS);
-        ostream.println(INDENT + "default locale = " + locale.getDisplayLanguage());
+        ostream.println(INDENT + "default locale = " +
+                locale.getDisplayLanguage());
+        ostream.println(INDENT + "default display locale = " +
+                Locale.getDefault(Category.DISPLAY).getDisplayName());
+        ostream.println(INDENT + "default format locale = " +
+                Locale.getDefault(Category.FORMAT).getDisplayName());
         printLocales(ostream);
         ostream.println();
     }
 
     private static void printLocales(PrintStream ostream) {
-        Locale[] locales = Locale.getAvailableLocales();
-        final int len = locales == null ? 0 : locales.length;
+        Locale[] tlocales = Locale.getAvailableLocales();
+        final int len = tlocales == null ? 0 : tlocales.length;
         if (len < 1 ) {
             return;
         }
+        // Locale does not implement Comparable so we convert it to String
+        // and sort it for pretty printing.
+        Set<String> sortedSet = new TreeSet<>();
+        for (Locale l : tlocales) {
+            sortedSet.add(l.toString());
+        }
+
         ostream.print(INDENT + "available locales = ");
-        final int last = len - 1 ;
-        for (int i = 0; i < last ; i++) {
-            ostream.print(locales[i]);
+        Iterator<String> iter = sortedSet.iterator();
+        final int last = len - 1;
+        for (int i = 0 ; iter.hasNext() ; i++) {
+            String s = iter.next();
+            ostream.print(s);
             if (i != last) {
                 ostream.print(", ");
             }
@@ -260,7 +265,42 @@
                 ostream.print(INDENT + INDENT);
             }
         }
-        ostream.println(locales[last]);
+    }
+
+    private enum SizePrefix {
+
+        KILO(1024, "K"),
+        MEGA(1024 * 1024, "M"),
+        GIGA(1024 * 1024 * 1024, "G"),
+        TERA(1024L * 1024L * 1024L * 1024L, "T");
+        long size;
+        String abbrev;
+
+        SizePrefix(long size, String abbrev) {
+            this.size = size;
+            this.abbrev = abbrev;
+        }
+
+        private static String scale(long v, SizePrefix prefix) {
+            return BigDecimal.valueOf(v).divide(BigDecimal.valueOf(prefix.size),
+                    2, RoundingMode.HALF_EVEN).toPlainString() + prefix.abbrev;
+        }
+        /*
+         * scale the incoming values to a human readable form, represented as
+         * K, M, G and T, see java.c parse_size for the scaled values and
+         * suffixes. The lowest possible scaled value is Kilo.
+         */
+        static String scaleValue(long v) {
+            if (v < MEGA.size) {
+                return scale(v, KILO);
+            } else if (v < GIGA.size) {
+                return scale(v, MEGA);
+            } else if (v < TERA.size) {
+                return scale(v, GIGA);
+            } else {
+                return scale(v, TERA);
+            }
+        }
     }
 
     /**
diff --git a/src/share/classes/sun/security/jgss/krb5/CipherHelper.java b/src/share/classes/sun/security/jgss/krb5/CipherHelper.java
index ade8bbf..51172ca 100644
--- a/src/share/classes/sun/security/jgss/krb5/CipherHelper.java
+++ b/src/share/classes/sun/security/jgss/krb5/CipherHelper.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 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
@@ -710,29 +710,21 @@
      * where HMAC is on {16-byte confounder | plaintext | 16-byte token_header}
      * HMAC is not encrypted; it is appended at the end.
      */
-    void encryptData(WrapToken_v2 token, byte[] confounder, byte[] tokenHeader,
-        byte[] plaintext, int start, int len, int key_usage, OutputStream os)
-        throws GSSException, IOException {
+    byte[] encryptData(WrapToken_v2 token, byte[] confounder, byte[] tokenHeader,
+            byte[] plaintext, int start, int len, int key_usage)
+            throws GSSException {
 
-        byte[] ctext = null;
         switch (etype) {
-                case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96:
-                    ctext = aes128Encrypt(confounder, tokenHeader,
-                                plaintext, start, len, key_usage);
-                    break;
-                case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96:
-                    ctext = aes256Encrypt(confounder, tokenHeader,
-                                plaintext, start, len, key_usage);
-                    break;
-                default:
-                    throw new GSSException(GSSException.FAILURE, -1,
-                        "Unsupported etype: " + etype);
+            case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96:
+                return aes128Encrypt(confounder, tokenHeader,
+                            plaintext, start, len, key_usage);
+            case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96:
+                return aes256Encrypt(confounder, tokenHeader,
+                            plaintext, start, len, key_usage);
+            default:
+                throw new GSSException(GSSException.FAILURE, -1,
+                    "Unsupported etype: " + etype);
         }
-
-        // Krb5Token.debug("EncryptedData = " +
-        //              Krb5Token.getHexBytes(ctext) + "\n");
-        // Write to stream
-        os.write(ctext);
     }
 
     void encryptData(WrapToken token, byte[] confounder, byte[] plaintext,
diff --git a/src/share/classes/sun/security/jgss/krb5/MessageToken_v2.java b/src/share/classes/sun/security/jgss/krb5/MessageToken_v2.java
index 7f5c2cf..d76a58b 100644
--- a/src/share/classes/sun/security/jgss/krb5/MessageToken_v2.java
+++ b/src/share/classes/sun/security/jgss/krb5/MessageToken_v2.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 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,42 +26,40 @@
 package sun.security.jgss.krb5;
 
 import org.ietf.jgss.*;
-import sun.security.jgss.*;
-import sun.security.krb5.*;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.IOException;
 import java.io.ByteArrayInputStream;
-import java.security.GeneralSecurityException;
+import java.io.ByteArrayOutputStream;
 import java.security.MessageDigest;
+import java.util.Arrays;
 
 /**
  * This class is a base class for new GSS token definitions, as defined
- * in draft-ietf-krb-wg-gssapi-cfx-07.txt, that pertain to per-message
- * GSS-API calls. Conceptually GSS-API has two types of per-message tokens:
- * WrapToken and MicToken. They differ in the respect that a WrapToken
- * carries additional plaintext or ciphertext application data besides
- * just the sequence number and checksum. This class encapsulates the
- * commonality in the structure of the WrapToken and the MicToken.
- * This structure can be represented as:
+ * in RFC 4121, that pertain to per-message GSS-API calls. Conceptually
+ * GSS-API has two types of per-message tokens: WrapToken and MicToken.
+ * They differ in the respect that a WrapToken carries additional plaintext
+ * or ciphertext application data besides just the sequence number and
+ * checksum. This class encapsulates the commonality in the structure of
+ * the WrapToken and the MicToken. This structure can be represented as:
  * <p>
  * <pre>
- *  Wrap Tokens
+ * Wrap Tokens
  *
  *     Octet no   Name        Description
  *    ---------------------------------------------------------------
  *      0..1     TOK_ID     Identification field.  Tokens emitted by
- *                          GSS_Wrap() contain the the hex value 05 04
- *                          expressed in big endian order in this field.
+ *                          GSS_Wrap() contain the hex value 05 04
+ *                          expressed in big-endian order in this field.
  *      2        Flags      Attributes field, as described in section
  *                          4.2.2.
  *      3        Filler     Contains the hex value FF.
- *      4..5     EC         Contains the "extra count" field, in big
+ *      4..5     EC         Contains the "extra count" field, in big-
  *                          endian order as described in section 4.2.3.
  *      6..7     RRC        Contains the "right rotation count" in big
  *                          endian order, as described in section 4.2.5.
  *      8..15    SND_SEQ    Sequence number field in clear text,
- *                          expressed in big endian order.
+ *                          expressed in big-endian order.
  *      16..last Data       Encrypted data for Wrap tokens with
  *                          confidentiality, or plaintext data followed
  *                          by the checksum for Wrap tokens without
@@ -73,67 +71,82 @@
  *     -----------------------------------------------------------------
  *      0..1     TOK_ID     Identification field.  Tokens emitted by
  *                          GSS_GetMIC() contain the hex value 04 04
- *                          expressed in big endian order in this field.
+ *                          expressed in big-endian order in this field.
  *      2        Flags      Attributes field, as described in section
  *                          4.2.2.
  *      3..7     Filler     Contains five octets of hex value FF.
  *      8..15    SND_SEQ    Sequence number field in clear text,
- *                          expressed in big endian order.
+ *                          expressed in big-endian order.
  *      16..last SGN_CKSUM  Checksum of the "to-be-signed" data and
  *                          octet 0..15, as described in section 4.2.4.
  *
  * </pre>
  * <p>
+ * This class is the super class of WrapToken_v2 and MicToken_v2. The token's
+ * header (bytes[0..15]) and data (byte[16..]) are saved in tokenHeader and
+ * tokenData fields. Since there is no easy way to find out the exact length
+ * of a WrapToken_v2 token from any header info, in the case of reading from
+ * stream, we read all available() bytes into the token.
+ * <p>
+ * All read actions are performed in this super class. On the write part, the
+ * super class only write the tokenHeader, and the content writing is inside
+ * child classes.
  *
  * @author Seema Malkani
  */
 
 abstract class MessageToken_v2 extends Krb5Token {
 
+    protected static final int TOKEN_HEADER_SIZE = 16;
     private static final int TOKEN_ID_POS = 0;
     private static final int TOKEN_FLAG_POS = 2;
     private static final int TOKEN_EC_POS = 4;
     private static final int TOKEN_RRC_POS = 6;
 
-    // token header size
-    static final int TOKEN_HEADER_SIZE = 16;
+    /**
+     * The size of the random confounder used in a WrapToken.
+     */
+    protected static final int CONFOUNDER_SIZE = 16;
 
-    private int tokenId = 0;
-    private int seqNumber;
-
-    // EC and RRC fields
-    private int ec = 0;
-    private int rrc = 0;
-
-    private boolean confState = true;
-    private boolean initiator = true;
-
-    byte[] confounder = null;
-    byte[] checksum = null;
-
-    private int key_usage = 0;
-    private byte[] seqNumberData = null;
-
-    private MessageTokenHeader tokenHeader = null;
-
-    /* cipher instance used by the corresponding GSSContext */
-    CipherHelper cipherHelper = null;
-
-    // draft-ietf-krb-wg-gssapi-cfx-07
+    // RFC 4121, key usage values
     static final int KG_USAGE_ACCEPTOR_SEAL = 22;
     static final int KG_USAGE_ACCEPTOR_SIGN = 23;
     static final int KG_USAGE_INITIATOR_SEAL = 24;
     static final int KG_USAGE_INITIATOR_SIGN = 25;
 
-    // draft-ietf-krb-wg-gssapi-cfx-07
+    // RFC 4121, Flags Field
     private static final int FLAG_SENDER_IS_ACCEPTOR = 1;
     private static final int FLAG_WRAP_CONFIDENTIAL  = 2;
     private static final int FLAG_ACCEPTOR_SUBKEY    = 4;
     private static final int FILLER = 0xff;
 
+    private MessageTokenHeader tokenHeader = null;
+
+    // Common field
+    private int tokenId = 0;
+    private int seqNumber;
+    protected byte[] tokenData; // content of token, without the header
+    protected int tokenDataLen;
+
+    // Key usage number for crypto action
+    private int key_usage = 0;
+
+    // EC and RRC fields, WrapToken only
+    private int ec = 0;
+    private int rrc = 0;
+
+    // Checksum. Always in MicToken, might be in WrapToken
+    byte[] checksum = null;
+
+    // Context properties
+    private boolean confState = true;
+    private boolean initiator = true;
+
+    /* cipher instance used by the corresponding GSSContext */
+    CipherHelper cipherHelper = null;
+
     /**
-     * Constructs a MessageToken from a byte array. If there are more bytes
-     * in the array than needed, the extra bytes are simply ignroed.
+     * Constructs a MessageToken from a byte array.
      *
      * @param tokenId the token id that should be contained in this token as
      * it is read.
@@ -156,7 +169,9 @@
     /**
      * Constructs a MessageToken from an InputStream. Bytes will be read on
      * demand and the thread might block if there are not enough bytes to
-     * complete the token.
+     * complete the token. Please note there is no accurate way to find out
+     * the size of a token, but we try our best to make sure there is
+     * enough bytes to construct one.
      *
      * @param tokenId the token id that should be contained in this token as
      * it is read.
@@ -186,25 +201,58 @@
                                 : KG_USAGE_ACCEPTOR_SIGN);
             }
 
-            // Read checksum
-            int tokenLen = is.available();
-            byte[] data = new byte[tokenLen];
-            readFully(is, data);
-            checksum = new byte[cipherHelper.getChecksumLength()];
-            System.arraycopy(data, tokenLen-cipherHelper.getChecksumLength(),
-                        checksum, 0, cipherHelper.getChecksumLength());
-            // debug("\nLeaving MessageToken.Cons\n");
+            int minSize = 0;    // minimal size for token data
+            if (tokenId == Krb5Token.WRAP_ID_v2 && prop.getPrivacy()) {
+                minSize = CONFOUNDER_SIZE +
+                        TOKEN_HEADER_SIZE + cipherHelper.getChecksumLength();
+            } else {
+                minSize = cipherHelper.getChecksumLength();
+            }
 
-            // validate EC for Wrap tokens without confidentiality
-            if (!prop.getPrivacy() &&
-                (tokenId == Krb5Token.WRAP_ID_v2)) {
-                if (checksum.length != ec) {
-                    throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
-                        getTokenName(tokenId) + ":" + "EC incorrect!");
+            // Read token data
+            if (tokenId == Krb5Token.MIC_ID_v2) {
+                // The only case we can precisely predict the token data length
+                tokenDataLen = minSize;
+                tokenData = new byte[minSize];
+                readFully(is, tokenData);
+            } else {
+                tokenDataLen = is.available();
+                if (tokenDataLen >= minSize) {  // read in one shot
+                    tokenData = new byte[tokenDataLen];
+                    readFully(is, tokenData);
+                } else {
+                    byte[] tmp = new byte[minSize];
+                    readFully(is, tmp);
+                    // Hope while blocked in the read above, more data would
+                    // come and is.available() below contains the whole token.
+                    int more = is.available();
+                    tokenDataLen = minSize + more;
+                    tokenData = Arrays.copyOf(tmp, tokenDataLen);
+                    readFully(is, tokenData, minSize, more);
                 }
             }
 
+            if (tokenId == Krb5Token.WRAP_ID_v2) {
+                // Does non-confidential data needs a rotate?
+                rotate();
+            }
 
+            if (tokenId == Krb5Token.MIC_ID_v2 ||
+                    (tokenId == Krb5Token.WRAP_ID_v2 && !prop.getPrivacy())) {
+                // Read checksum
+                int chkLen = cipherHelper.getChecksumLength();
+                checksum = new byte[chkLen];
+                System.arraycopy(tokenData, tokenDataLen-chkLen,
+                        checksum, 0, chkLen);
+
+                // validate EC for Wrap tokens without confidentiality
+                if (tokenId == Krb5Token.WRAP_ID_v2 && !prop.getPrivacy()) {
+                    if (chkLen != ec) {
+                        throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
+                            getTokenName(tokenId) + ":" + "EC incorrect!");
+                    }
+                }
+            }
         } catch (IOException e) {
             throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
                 getTokenName(tokenId) + ":" + e.getMessage());
@@ -263,8 +311,7 @@
             prop.setPrivacy(false);
         }
 
-        // Create a new gss token header as defined in
-        // draft-ietf-krb-wg-gssapi-cfx-07
+        // Create a new gss token header as defined in RFC 4121
         tokenHeader = new MessageTokenHeader(tokenId,
                                 prop.getPrivacy(), true);
         // debug("\n\t Message Header = " +
@@ -326,50 +373,21 @@
      * Rotate bytes as per the "RRC" (Right Rotation Count) received.
      * Our implementation does not do any rotates when sending, only
      * when receiving, we rotate left as per the RRC count, to revert it.
-     *
-     * @return true if bytes are rotated
      */
-    public boolean rotate_left(byte[] in_bytes, int tokenOffset,
-        byte[] out_bytes, int bufsize) {
+    private void rotate() {
+        if (rrc % tokenDataLen != 0) {
+           rrc = rrc % tokenDataLen;
+           byte[] newBytes = new byte[tokenDataLen];
 
-        int offset = 0;
-        // debug("\nRotate left: (before rotation) in_bytes = [ " +
-        //              getHexBytes(in_bytes, tokenOffset, bufsize) + "]");
-        if (rrc > 0) {
-           if (bufsize == 0) {
-                return false;
-           }
-           rrc = rrc % (bufsize - TOKEN_HEADER_SIZE);
-           if (rrc == 0) {
-                return false;
-           }
+           System.arraycopy(tokenData, rrc, newBytes, 0, tokenDataLen-rrc);
+           System.arraycopy(tokenData, 0, newBytes, tokenDataLen-rrc, rrc);
 
-           // if offset is not zero
-           if (tokenOffset > 0) {
-                offset += tokenOffset;
-           }
-
-           // copy the header
-           System.arraycopy(in_bytes, offset, out_bytes, 0, TOKEN_HEADER_SIZE);
-           offset += TOKEN_HEADER_SIZE;
-
-           // copy rest of the bytes
-           System.arraycopy(in_bytes, offset+rrc, out_bytes,
-                        TOKEN_HEADER_SIZE, bufsize-TOKEN_HEADER_SIZE-rrc);
-
-           // copy the bytes specified by rrc count
-           System.arraycopy(in_bytes, offset, out_bytes,
-                        bufsize-TOKEN_HEADER_SIZE-rrc, rrc);
-
-           // debug("\nRotate left: (after rotation) out_bytes = [ " +
-           //           getHexBytes(out_bytes, 0, bufsize) + "]");
-           return true;
+           tokenData = newBytes;
         }
-        return false;
     }
 
     public final int getSequenceNumber() {
-        return (readBigEndian(seqNumberData, 0, 4));
+        return seqNumber;
     }
 
     /**
@@ -444,44 +462,25 @@
 
         this.cipherHelper = context.getCipherHelper(null);
         //    debug("In MessageToken.Cons");
-
-        // draft-ietf-krb-wg-gssapi-cfx-07
-        this.tokenId = tokenId;
     }
 
     /**
-     * Encodes a GSSHeader and this token onto an OutputStream.
+     * Encodes a MessageTokenHeader onto an OutputStream.
      *
      * @param os the OutputStream to which this should be written
-     * @throws GSSException if an error occurs while writing to the OutputStream
+     * @throws IOException is an error occurs while writing to the OutputStream
      */
-    public void encode(OutputStream os) throws IOException, GSSException {
-        // debug("Writing tokenHeader " + getHexBytes(tokenHeader.getBytes());
-        // (16 bytes of token header that includes sequence Number)
+    protected void encodeHeader(OutputStream os) throws IOException {
         tokenHeader.encode(os);
-        // debug("Writing checksum: " + getHexBytes(checksum));
-        if (tokenId == MIC_ID_v2) {
-           os.write(checksum);
-        }
     }
 
     /**
-     * Obtains the size of this token. Note that this excludes the size of
-     * the GSSHeader.
-     * @return token size
+     * Encodes a MessageToken_v2 onto an OutputStream.
+     *
+     * @param os the OutputStream to which this should be written
+     * @throws IOException is an error occurs while encoding the token
      */
-    protected int getKrb5TokenSize() throws GSSException {
-        return getTokenSize();
-    }
-
-    protected final int getTokenSize() throws GSSException {
-        return (TOKEN_HEADER_SIZE + cipherHelper.getChecksumLength());
-    }
-
-    protected static final int getTokenSize(CipherHelper ch)
-        throws GSSException {
-        return (TOKEN_HEADER_SIZE + ch.getChecksumLength());
-    }
+    public abstract void encode(OutputStream os) throws IOException;
 
     protected final byte[] getTokenHeader() {
         return (tokenHeader.getBytes());
@@ -493,45 +492,14 @@
 
     /**
      * This inner class represents the initial portion of the message token.
-     * It constitutes the first 16 bytes of the message token:
-     * <pre>
-     *  Wrap Tokens
-     *
-     *     Octet no   Name        Description
-     *    ---------------------------------------------------------------
-     *      0..1     TOK_ID     Identification field.  Tokens emitted by
-     *                          GSS_Wrap() contain the the hex value 05 04
-     *                          expressed in big endian order in this field.
-     *      2        Flags      Attributes field, as described in section
-     *                          4.2.2.
-     *      3        Filler     Contains the hex value FF.
-     *      4..5     EC         Contains the "extra count" field, in big
-     *                          endian order as described in section 4.2.3.
-     *      6..7     RRC        Contains the "right rotation count" in big
-     *                          endian order, as described in section 4.2.5.
-     *      8..15    SND_SEQ    Sequence number field in clear text,
-     *                          expressed in big endian order.
-     *
-     * MIC Tokens
-     *
-     *     Octet no   Name        Description
-     *     -----------------------------------------------------------------
-     *      0..1     TOK_ID     Identification field.  Tokens emitted by
-     *                          GSS_GetMIC() contain the hex value 04 04
-     *                          expressed in big endian order in this field.
-     *      2        Flags      Attributes field, as described in section
-     *                          4.2.2.
-     *      3..7     Filler     Contains five octets of hex value FF.
-     *      8..15    SND_SEQ    Sequence number field in clear text,
-     *                          expressed in big endian order.
-     * </pre>
+     * It constitutes the first 16 bytes of the message token.
      */
     class MessageTokenHeader {
 
          private int tokenId;
          private byte[] bytes = new byte[TOKEN_HEADER_SIZE];
 
-         // new token header draft-ietf-krb-wg-gssapi-cfx-07
+         // Writes a new token header
          public MessageTokenHeader(int tokenId, boolean conf,
                 boolean have_acceptor_subkey) throws GSSException {
 
@@ -542,16 +510,15 @@
 
             // Flags (Note: MIT impl requires subkey)
             int flags = 0;
-            flags = ((initiator ? 0 : FLAG_SENDER_IS_ACCEPTOR) |
+            flags = (initiator ? 0 : FLAG_SENDER_IS_ACCEPTOR) |
                      ((conf && tokenId != MIC_ID_v2) ?
                                 FLAG_WRAP_CONFIDENTIAL : 0) |
-                     (have_acceptor_subkey ? FLAG_ACCEPTOR_SUBKEY : 0));
+                     (have_acceptor_subkey ? FLAG_ACCEPTOR_SUBKEY : 0);
             bytes[2] = (byte) flags;
 
             // filler
             bytes[3] = (byte) FILLER;
 
-            // EC and RRC fields
             if (tokenId == WRAP_ID_v2) {
                 // EC field
                 bytes[4] = (byte) 0;
@@ -560,21 +527,19 @@
                 bytes[6] = (byte) 0;
                 bytes[7] = (byte) 0;
             } else if (tokenId == MIC_ID_v2) {
-                // octets of filler FF
+                // more filler for MicToken
                 for (int i = 4; i < 8; i++) {
                     bytes[i] = (byte) FILLER;
                 }
             }
 
-            // Calculate SND_SEQ
-            seqNumberData = new byte[8];
-            writeBigEndian(seqNumber, seqNumberData, 4);
-            System.arraycopy(seqNumberData, 0, bytes, 8, 8);
+            // Calculate SND_SEQ, only write 4 bytes from the 12th position
+            writeBigEndian(seqNumber, bytes, 12);
         }
 
         /**
-         * Constructs a MessageTokenHeader by reading it from an InputStream
-         * and sets the appropriate confidentiality and quality of protection
+         * Reads a MessageTokenHeader from an InputStream and sets the
+         * appropriate confidentiality and quality of protection
          * values in a MessageProp structure.
          *
          * @param is the InputStream to read from
@@ -588,15 +553,23 @@
             readFully(is, bytes, 0, TOKEN_HEADER_SIZE);
             tokenId = readInt(bytes, TOKEN_ID_POS);
 
+            // validate Token ID
+            if (tokenId != tokId) {
+                throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
+                    getTokenName(tokenId) + ":" + "Defective Token ID!");
+            }
+
             /*
              * Validate new GSS TokenHeader
              */
-            // valid acceptor_flag is set
+
+            // valid acceptor_flag
+            // If I am initiator, the received token should have ACCEPTOR on
             int acceptor_flag = (initiator ? FLAG_SENDER_IS_ACCEPTOR : 0);
             int flag = bytes[TOKEN_FLAG_POS] & FLAG_SENDER_IS_ACCEPTOR;
-            if (!(flag == acceptor_flag)) {
+            if (flag != acceptor_flag) {
                 throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
-                        getTokenName(tokenId) + ":" + "Acceptor Flag Missing!");
+                        getTokenName(tokenId) + ":" + "Acceptor Flag Error!");
             }
 
             // check for confidentiality
@@ -608,21 +581,20 @@
                 prop.setPrivacy(false);
             }
 
-            // validate Token ID
-            if (tokenId != tokId) {
-                throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
-                    getTokenName(tokenId) + ":" + "Defective Token ID!");
-            }
+            if (tokenId == WRAP_ID_v2) {
+                // validate filler
+                if ((bytes[3] & 0xff) != FILLER) {
+                    throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
+                        getTokenName(tokenId) + ":" + "Defective Token Filler!");
+                }
 
-            // validate filler
-            if ((bytes[3] & 0xff) != FILLER) {
-                throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
-                    getTokenName(tokenId) + ":" + "Defective Token Filler!");
-            }
+                // read EC field
+                ec = readBigEndian(bytes, TOKEN_EC_POS, 2);
 
-            // validate next 4 bytes of filler for MIC tokens
-            if (tokenId == MIC_ID_v2) {
-                for (int i = 4; i < 8; i++) {
+                // read RRC field
+                rrc = readBigEndian(bytes, TOKEN_RRC_POS, 2);
+            } else if (tokenId == MIC_ID_v2) {
+                for (int i = 3; i < 8; i++) {
                     if ((bytes[i] & 0xff) != FILLER) {
                         throw new GSSException(GSSException.DEFECTIVE_TOKEN,
                                 -1, getTokenName(tokenId) + ":" +
@@ -631,18 +603,11 @@
                 }
             }
 
-            // read EC field
-            ec = readBigEndian(bytes, TOKEN_EC_POS, 2);
-
-            // read RRC field
-            rrc = readBigEndian(bytes, TOKEN_RRC_POS, 2);
-
             // set default QOP
             prop.setQOP(0);
 
             // sequence number
-            seqNumberData = new byte[8];
-            System.arraycopy(bytes, 8, seqNumberData, 0, 8);
+            seqNumber = readBigEndian(bytes, 0, 8);
         }
 
         /**
diff --git a/src/share/classes/sun/security/jgss/krb5/MicToken_v2.java b/src/share/classes/sun/security/jgss/krb5/MicToken_v2.java
index 3239001..bd4a263 100644
--- a/src/share/classes/sun/security/jgss/krb5/MicToken_v2.java
+++ b/src/share/classes/sun/security/jgss/krb5/MicToken_v2.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 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,12 +29,11 @@
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.IOException;
-import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 
 /**
  * This class represents the new format of GSS MIC tokens, as specified
- * in draft-ietf-krb-wg-gssapi-cfx-07.txt
+ * in RFC 4121
  *
  * MIC tokens = { 16-byte token-header |  HMAC }
  * where HMAC is on { plaintext | 16-byte token-header }
@@ -48,12 +47,11 @@
                   byte[] tokenBytes, int tokenOffset, int tokenLen,
                   MessageProp prop)  throws GSSException {
         super(Krb5Token.MIC_ID_v2, context,
-          tokenBytes, tokenOffset, tokenLen, prop);
+                tokenBytes, tokenOffset, tokenLen, prop);
     }
 
-    public MicToken_v2(Krb5Context context,
-                   InputStream is, MessageProp prop)
-    throws GSSException {
+    public MicToken_v2(Krb5Context context, InputStream is, MessageProp prop)
+            throws GSSException {
         super(Krb5Token.MIC_ID_v2, context, is, prop);
     }
 
@@ -64,7 +62,6 @@
     }
 
     public void verify(InputStream data) throws GSSException {
-
         byte[] dataBytes = null;
         try {
             dataBytes = new byte[data.available()];
@@ -79,7 +76,7 @@
 
     public MicToken_v2(Krb5Context context, MessageProp prop,
                   byte[] data, int pos, int len)
-        throws GSSException {
+            throws GSSException {
         super(Krb5Token.MIC_ID_v2, context);
 
         //      debug("Application data to MicToken verify is [" +
@@ -89,7 +86,7 @@
     }
 
     public MicToken_v2(Krb5Context context, MessageProp prop, InputStream data)
-        throws GSSException, IOException {
+            throws GSSException, IOException {
 
         super(Krb5Token.MIC_ID_v2, context);
         byte[] dataBytes = new byte[data.available()];
@@ -101,22 +98,21 @@
         genSignAndSeqNumber(prop, dataBytes, 0, dataBytes.length);
     }
 
-    public int encode(byte[] outToken, int offset)
-        throws IOException, GSSException {
-
-        // Token  is small
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        super.encode(bos);
-        byte[] token = bos.toByteArray();
-        System.arraycopy(token, 0, outToken, offset, token.length);
-        return token.length;
-    }
-
-    public byte[] encode() throws IOException, GSSException {
-
+    public byte[] encode() throws IOException {
         // XXX Fine tune this initial size
         ByteArrayOutputStream bos = new ByteArrayOutputStream(50);
         encode(bos);
         return bos.toByteArray();
     }
+
+    public int encode(byte[] outToken, int offset) throws IOException {
+        byte[] token = encode();
+        System.arraycopy(token, 0, outToken, offset, token.length);
+        return token.length;
+    }
+
+    public void encode(OutputStream os) throws IOException {
+        encodeHeader(os);
+        os.write(checksum);
+    }
 }
diff --git a/src/share/classes/sun/security/jgss/krb5/WrapToken.java b/src/share/classes/sun/security/jgss/krb5/WrapToken.java
index 0fc9880..154be82 100644
--- a/src/share/classes/sun/security/jgss/krb5/WrapToken.java
+++ b/src/share/classes/sun/security/jgss/krb5/WrapToken.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 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
@@ -27,14 +27,11 @@
 
 import org.ietf.jgss.*;
 import sun.security.jgss.*;
-import java.security.GeneralSecurityException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.IOException;
-import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import sun.security.krb5.Confounder;
-import sun.security.krb5.KrbException;
 
 /**
  * This class represents a token emitted by the GSSContext.wrap()
@@ -336,24 +333,29 @@
                 // debug("\t\tNo encryption was performed by peer.\n");
                 readFully(is, confounder);
 
-                // Data is always a multiple of 8 with this GSS Mech
-                // Copy all but last block as they are
-                int numBlocks = (dataSize - CONFOUNDER_SIZE)/8 - 1;
-                int offset = dataBufOffset;
-                for (int i = 0; i < numBlocks; i++) {
-                    readFully(is, dataBuf, offset, 8);
-                    offset += 8;
+                if (cipherHelper.isArcFour()) {
+                    padding = pads[1];
+                    readFully(is, dataBuf, dataBufOffset, dataSize-CONFOUNDER_SIZE-1);
+                } else {
+                    // Data is always a multiple of 8 with this GSS Mech
+                    // Copy all but last block as they are
+                    int numBlocks = (dataSize - CONFOUNDER_SIZE)/8 - 1;
+                    int offset = dataBufOffset;
+                    for (int i = 0; i < numBlocks; i++) {
+                        readFully(is, dataBuf, offset, 8);
+                        offset += 8;
+                    }
+
+                    byte[] finalBlock = new byte[8];
+                    readFully(is, finalBlock);
+
+                    int padSize = finalBlock[7];
+                    padding = pads[padSize];
+
+                    // debug("\t\tPadding applied was: " + padSize + "\n");
+                    System.arraycopy(finalBlock, 0, dataBuf, offset,
+                                     finalBlock.length - padSize);
                 }
-
-                byte[] finalBlock = new byte[8];
-                readFully(is, finalBlock);
-
-                int padSize = finalBlock[7];
-                padding = pads[padSize];
-
-                // debug("\t\tPadding applied was: " + padSize + "\n");
-                System.arraycopy(finalBlock, 0, dataBuf, offset,
-                                 finalBlock.length - padSize);
             }
         } catch (IOException e) {
             throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
diff --git a/src/share/classes/sun/security/jgss/krb5/WrapToken_v2.java b/src/share/classes/sun/security/jgss/krb5/WrapToken_v2.java
index 8112971..fa4de1d 100644
--- a/src/share/classes/sun/security/jgss/krb5/WrapToken_v2.java
+++ b/src/share/classes/sun/security/jgss/krb5/WrapToken_v2.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 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
@@ -27,66 +27,30 @@
 
 import org.ietf.jgss.*;
 import sun.security.jgss.*;
-import java.security.GeneralSecurityException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.IOException;
-import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
+import java.util.Arrays;
 import sun.security.krb5.Confounder;
-import sun.security.krb5.KrbException;
 
 /**
- * This class represents the new format of GSS tokens, as specified in
- * draft-ietf-krb-wg-gssapi-cfx-07.txt, emitted by the GSSContext.wrap()
- * call. It is a MessageToken except that it also contains plaintext or
- * encrypted data at the end. A WrapToken has certain other rules that are
- * peculiar to it and different from a  MICToken, which is another type of
- * MessageToken. All data in a WrapToken is prepended by a random counfounder
- * of 16 bytes. Thus, all application data is replaced by
- * (confounder || data || tokenHeader || checksum).
+ * This class represents the new format of GSS tokens, as specified in RFC
+ * 4121, emitted by the GSSContext.wrap() call. It is a MessageToken except
+ * that it also contains plaintext or encrypted data at the end. A WrapToken
+ * has certain other rules that are peculiar to it and different from a
+ * MICToken, which is another type of MessageToken. All data in a WrapToken is
+ * prepended by a random confounder of 16 bytes. Thus, all application data
+ * is replaced by (confounder || data || tokenHeader || checksum).
  *
  * @author Seema Malkani
  */
 class WrapToken_v2 extends MessageToken_v2 {
-    /**
-     * The size of the random confounder used in a WrapToken.
-     */
-    static final int CONFOUNDER_SIZE = 16;
-
-    /*
-     * A token may come in either in an InputStream or as a
-     * byte[]. Store a reference to it in either case and process
-     * it's data only later when getData() is called and
-     * decryption/copying is needed to be done. Note that JCE can
-     * decrypt both from a byte[] and from an InputStream.
-     */
-    private boolean readTokenFromInputStream = true;
-    private InputStream is = null;
-    private byte[] tokenBytes = null;
-    private int tokenOffset = 0;
-    private int tokenLen = 0;
-
-    /*
-     * Application data may come from an InputStream or from a
-     * byte[]. However, it will always be stored and processed as a
-     * byte[] since
-     * (a) the MessageDigest class only accepts a byte[] as input and
-     * (b) It allows writing to an OuputStream via a CipherOutputStream.
-     */
-    private byte[] dataBytes = null;
-    private int dataOffset = 0;
-    private int dataLen = 0;
-
-    // the len of the token data:
-    //          (confounder || data || tokenHeader || checksum)
-    private int dataSize = 0;
 
     // Accessed by CipherHelper
     byte[] confounder = null;
 
-    private boolean privacy = false;
-    private boolean initiator = true;
+    private final boolean privacy;
 
     /**
      * Constructs a WrapToken from token bytes obtained from the
@@ -104,30 +68,9 @@
                      byte[] tokenBytes, int tokenOffset, int tokenLen,
                      MessageProp prop)  throws GSSException {
 
-        // Just parse the MessageToken part first
         super(Krb5Token.WRAP_ID_v2, context,
               tokenBytes, tokenOffset, tokenLen, prop);
-        this.readTokenFromInputStream = false;
-
-        // rotate token bytes as per RRC
-        byte[] new_tokenBytes = new byte[tokenLen];
-        if (rotate_left(tokenBytes, tokenOffset, new_tokenBytes, tokenLen)) {
-            this.tokenBytes = new_tokenBytes;
-            this.tokenOffset = 0;
-        } else {
-            this.tokenBytes = tokenBytes;
-            this.tokenOffset = tokenOffset;
-        }
-
-        // Will need the token bytes again when extracting data
-        this.tokenLen = tokenLen;
         this.privacy = prop.getPrivacy();
-
-        dataSize = tokenLen - TOKEN_HEADER_SIZE;
-
-        // save initiator
-        this.initiator = context.isInitiator();
-
     }
 
     /**
@@ -145,27 +88,8 @@
                      InputStream is, MessageProp prop)
         throws GSSException {
 
-        // Just parse the MessageToken part first
         super(Krb5Token.WRAP_ID_v2, context, is, prop);
-
-        // Will need the token bytes again when extracting data
-        this.is = is;
         this.privacy = prop.getPrivacy();
-
-        // get the token length
-        try {
-            this.tokenLen = is.available();
-        } catch (IOException e) {
-            throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
-                                   getTokenName(getTokenId())
-                                   + ": " + e.getMessage());
-        }
-
-        // data size
-        dataSize = tokenLen - TOKEN_HEADER_SIZE;
-
-        // save initiator
-        this.initiator = context.isInitiator();
     }
 
     /**
@@ -177,13 +101,9 @@
      */
     public byte[] getData() throws GSSException {
 
-        byte[] temp = new byte[dataSize];
+        byte[] temp = new byte[tokenDataLen];
         int len = getData(temp, 0);
-        // len obtained is after removing confounder, tokenHeader and HMAC
-
-        byte[] retVal = new byte[len];
-        System.arraycopy(temp, 0, retVal, 0, retVal.length);
-        return retVal;
+        return Arrays.copyOf(temp, len);
     }
 
     /**
@@ -200,69 +120,26 @@
     public int getData(byte[] dataBuf, int dataBufOffset)
         throws GSSException {
 
-        if (readTokenFromInputStream)
-            getDataFromStream(dataBuf, dataBufOffset);
-        else
-            getDataFromBuffer(dataBuf, dataBufOffset);
-
-        int retVal = 0;
-        if (privacy) {
-            retVal = dataSize - confounder.length -
-                TOKEN_HEADER_SIZE - cipherHelper.getChecksumLength();
-        } else {
-            retVal = dataSize - cipherHelper.getChecksumLength();
-        }
-        return retVal;
-    }
-
-    /**
-     * Helper routine to obtain the application data transmitted in
-     * this WrapToken. It is called if the WrapToken was constructed
-     * with a byte array as input.
-     * @param dataBuf the output buffer into which the data must be
-     * written
-     * @param dataBufOffset the offset at which to write the data
-     * @throws GSSException if an error occurs while decrypting any
-     * cipher text and checking for validity
-     */
-    private void getDataFromBuffer(byte[] dataBuf, int dataBufOffset)
-        throws GSSException {
-
-        int dataPos = tokenOffset + TOKEN_HEADER_SIZE;
-        int data_length = 0;
-
-        if (dataPos + dataSize > tokenOffset + tokenLen)
-            throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
-                                   "Insufficient data in "
-                                   + getTokenName(getTokenId()));
         // debug("WrapToken cons: data is token is [" +
         //      getHexBytes(tokenBytes, tokenOffset, tokenLen) + "]\n");
-        confounder = new byte[CONFOUNDER_SIZE];
 
         // Do decryption if this token was privacy protected.
         if (privacy) {
 
             // decrypt data
-            cipherHelper.decryptData(this, tokenBytes, dataPos, dataSize,
+            cipherHelper.decryptData(this, tokenData, 0, tokenDataLen,
                                 dataBuf, dataBufOffset, getKeyUsage());
-            /*
-            debug("\t\tDecrypted data is [" +
-                getHexBytes(confounder) + " " +
-                getHexBytes(dataBuf, dataBufOffset,
-                dataSize - CONFOUNDER_SIZE) +
-                "]\n");
-            */
 
-            data_length = dataSize - CONFOUNDER_SIZE -
-                        TOKEN_HEADER_SIZE - cipherHelper.getChecksumLength();
+            return tokenDataLen - CONFOUNDER_SIZE -
+                TOKEN_HEADER_SIZE - cipherHelper.getChecksumLength();
         } else {
 
             // Token data is in cleartext
-            debug("\t\tNo encryption was performed by peer.\n");
+            // debug("\t\tNo encryption was performed by peer.\n");
 
             // data
-            data_length = dataSize - cipherHelper.getChecksumLength();
-            System.arraycopy(tokenBytes, dataPos,
+            int data_length = tokenDataLen - cipherHelper.getChecksumLength();
+            System.arraycopy(tokenData, 0,
                              dataBuf, dataBufOffset,
                              data_length);
             // debug("\t\tData is: " + getHexBytes(dataBuf, data_length));
@@ -274,95 +151,26 @@
                 throw new GSSException(GSSException.BAD_MIC, -1,
                          "Corrupt checksum in Wrap token");
             }
+            return data_length;
         }
     }
 
     /**
-     * Helper routine to obtain the application data transmitted in
-     * this WrapToken. It is called if the WrapToken was constructed
-     * with an Inputstream.
-     * @param dataBuf the output buffer into which the data must be
-     * written
-     * @param dataBufOffset the offset at which to write the data
-     * @throws GSSException if an error occurs while decrypting any
-     * cipher text and checking for validity
+     * Writes a WrapToken_v2 object
      */
-    private void getDataFromStream(byte[] dataBuf, int dataBufOffset)
-        throws GSSException {
-
-        int data_length = 0;
-        // Don't check the token length. Data will be read on demand from
-        // the InputStream.
-        // debug("WrapToken cons: data will be read from InputStream.\n");
-
-        confounder = new byte[CONFOUNDER_SIZE];
-
-        try {
-            // Do decryption if this token was privacy protected.
-            if (privacy) {
-
-                cipherHelper.decryptData(this, is, dataSize,
-                    dataBuf, dataBufOffset, getKeyUsage());
-
-                /*
-                debug("\t\tDecrypted data is [" +
-                     getHexBytes(confounder) + " " +
-                     getHexBytes(dataBuf, dataBufOffset,
-                  dataSize - CONFOUNDER_SIZE) +
-                     "]\n");
-                */
-                data_length = dataSize - CONFOUNDER_SIZE -
-                        TOKEN_HEADER_SIZE - cipherHelper.getChecksumLength();
-            } else {
-
-                // Token data is in cleartext
-                debug("\t\tNo encryption was performed by peer.\n");
-                readFully(is, confounder);
-
-                // read the data
-                data_length = dataSize - cipherHelper.getChecksumLength();
-                readFully(is, dataBuf, dataBufOffset, data_length);
-
-                /*
-                 * Make sure checksum is not corrupt
-                 */
-                if (!verifySign(dataBuf, dataBufOffset, data_length)) {
-                    throw new GSSException(GSSException.BAD_MIC, -1,
-                         "Corrupt checksum in Wrap token");
-                }
-            }
-        } catch (IOException e) {
-            throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
-                                   getTokenName(getTokenId())
-                                   + ": " + e.getMessage());
-        }
-
-    }
-
-
     public WrapToken_v2(Krb5Context context, MessageProp prop,
                      byte[] dataBytes, int dataOffset, int dataLen)
-        throws GSSException {
+            throws GSSException {
 
         super(Krb5Token.WRAP_ID_v2, context);
 
         confounder = Confounder.bytes(CONFOUNDER_SIZE);
 
-        dataSize = confounder.length + dataLen + TOKEN_HEADER_SIZE +
-                        cipherHelper.getChecksumLength();
-        this.dataBytes = dataBytes;
-        this.dataOffset = dataOffset;
-        this.dataLen = dataLen;
-
-        // save initiator
-        this.initiator = context.isInitiator();
-
         // debug("\nWrapToken cons: data to wrap is [" +
         // getHexBytes(confounder) + " " +
         // getHexBytes(dataBytes, dataOffset, dataLen) + "]\n");
 
-        genSignAndSeqNumber(prop,
-                            dataBytes, dataOffset, dataLen);
+        genSignAndSeqNumber(prop, dataBytes, dataOffset, dataLen);
 
         /*
          * If the application decides to ask for privacy when the context
@@ -374,110 +182,42 @@
             prop.setPrivacy(false);
 
         privacy = prop.getPrivacy();
-    }
 
-    public void encode(OutputStream os) throws IOException, GSSException {
-
-        super.encode(os);
-
-        // debug("\n\nWriting data: [");
         if (!privacy) {
-
             // Wrap Tokens (without confidentiality) =
             // { 16 byte token_header | plaintext | 12-byte HMAC }
             // where HMAC is on { plaintext | token_header }
 
-            // calculate checksum
-            byte[] checksum = getChecksum(dataBytes, dataOffset, dataLen);
-
-            // data
-            // debug(" " + getHexBytes(dataBytes, dataOffset, dataLen));
-            os.write(dataBytes, dataOffset, dataLen);
-
-            // write HMAC
-            // debug(" " + getHexBytes(checksum,
-            //                  cipherHelper.getChecksumLength()));
-            os.write(checksum);
-
+            tokenData = new byte[dataLen + checksum.length];
+            System.arraycopy(dataBytes, dataOffset, tokenData, 0, dataLen);
+            System.arraycopy(checksum, 0, tokenData, dataLen, checksum.length);
         } else {
-
             // Wrap Tokens (with confidentiality) =
             // { 16 byte token_header |
             // Encrypt(16-byte confounder | plaintext | token_header) |
             // 12-byte HMAC }
 
-            cipherHelper.encryptData(this, confounder, getTokenHeader(),
-                dataBytes, dataOffset, dataLen, getKeyUsage(), os);
-
+            tokenData = cipherHelper.encryptData(this, confounder, getTokenHeader(),
+                dataBytes, dataOffset, dataLen, getKeyUsage());
         }
-        // debug("]\n");
     }
 
-    public byte[] encode() throws IOException, GSSException {
-        // XXX Fine tune this initial size
-        ByteArrayOutputStream bos = new ByteArrayOutputStream(dataSize + 50);
+    public void encode(OutputStream os) throws IOException {
+        encodeHeader(os);
+        os.write(tokenData);
+    }
+
+    public byte[] encode() throws IOException {
+        ByteArrayOutputStream bos = new ByteArrayOutputStream(
+                MessageToken_v2.TOKEN_HEADER_SIZE + tokenData.length);
         encode(bos);
         return bos.toByteArray();
     }
 
-    public int encode(byte[] outToken, int offset)
-        throws IOException, GSSException  {
-
-        int retVal = 0;
-
-        // Token header is small
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        super.encode(bos);
-        byte[] header = bos.toByteArray();
-        System.arraycopy(header, 0, outToken, offset, header.length);
-        offset += header.length;
-
-        // debug("WrapToken.encode: Writing data: [");
-        if (!privacy) {
-
-            // Wrap Tokens (without confidentiality) =
-            // { 16 byte token_header | plaintext | 12-byte HMAC }
-            // where HMAC is on { plaintext | token_header }
-
-            // calculate checksum
-            byte[] checksum = getChecksum(dataBytes, dataOffset, dataLen);
-
-            // data
-            // debug(" " + getHexBytes(dataBytes, dataOffset, dataLen));
-            System.arraycopy(dataBytes, dataOffset, outToken, offset,
-                             dataLen);
-            offset += dataLen;
-
-            // write HMAC
-            // debug(" " + getHexBytes(checksum,
-            //                  cipherHelper.getChecksumLength()));
-            System.arraycopy(checksum, 0, outToken, offset,
-                                cipherHelper.getChecksumLength());
-
-            retVal = header.length + dataLen + cipherHelper.getChecksumLength();
-        } else {
-
-            // Wrap Tokens (with confidentiality) =
-            // { 16 byte token_header |
-            // Encrypt(16-byte confounder | plaintext | token_header) |
-            // 12-byte HMAC }
-            int cLen = cipherHelper.encryptData(this, confounder,
-                        getTokenHeader(), dataBytes, dataOffset, dataLen,
-                        outToken, offset, getKeyUsage());
-
-            retVal = header.length + cLen;
-            // debug(getHexBytes(outToken, offset, dataSize));
-        }
-
-        // debug("]\n");
-
-        // %%% assume that plaintext length == ciphertext len
-        return retVal;
-
-    }
-
-    protected int getKrb5TokenSize() throws GSSException {
-        return (getTokenSize() + dataSize);
+    public int encode(byte[] outToken, int offset) throws IOException {
+        byte[] token = encode();
+        System.arraycopy(token, 0, outToken, offset, token.length);
+        return token.length;
     }
 
     // This implementation is way to conservative. And it certainly
@@ -485,6 +225,7 @@
     static int getSizeLimit(int qop, boolean confReq, int maxTokenSize,
         CipherHelper ch) throws GSSException {
         return (GSSHeader.getMaxMechTokenSize(OID, maxTokenSize) -
-                (getTokenSize(ch) + CONFOUNDER_SIZE) - 8 /* safety */);
+                (TOKEN_HEADER_SIZE + ch.getChecksumLength() + CONFOUNDER_SIZE)
+                - 8 /* safety */);
     }
 }
diff --git a/src/share/classes/sun/security/pkcs11/Config.java b/src/share/classes/sun/security/pkcs11/Config.java
index 940a4c5..243f49d 100644
--- a/src/share/classes/sun/security/pkcs11/Config.java
+++ b/src/share/classes/sun/security/pkcs11/Config.java
@@ -343,6 +343,7 @@
         st.wordChars('{', '{'); // need {} for property subst
         st.wordChars('}', '}');
         st.wordChars('*', '*');
+        st.wordChars('~', '~');
         // XXX check ASCII table and add all other characters except special
 
         // special: #="(),
diff --git a/src/share/classes/sun/security/pkcs11/P11Cipher.java b/src/share/classes/sun/security/pkcs11/P11Cipher.java
index 5568887..3d2525f 100644
--- a/src/share/classes/sun/security/pkcs11/P11Cipher.java
+++ b/src/share/classes/sun/security/pkcs11/P11Cipher.java
@@ -395,6 +395,8 @@
             }
         } catch (PKCS11Exception e) {
             throw new ProviderException("Cancel failed", e);
+        } finally {
+            reset();
         }
     }
 
@@ -408,12 +410,18 @@
         if (session == null) {
             session = token.getOpSession();
         }
-        if (encrypt) {
-            token.p11.C_EncryptInit(session.id(),
-                    new CK_MECHANISM(mechanism, iv), p11Key.keyID);
-        } else {
-            token.p11.C_DecryptInit(session.id(),
-                    new CK_MECHANISM(mechanism, iv), p11Key.keyID);
+        try {
+            if (encrypt) {
+                token.p11.C_EncryptInit(session.id(),
+                        new CK_MECHANISM(mechanism, iv), p11Key.keyID);
+            } else {
+                token.p11.C_DecryptInit(session.id(),
+                        new CK_MECHANISM(mechanism, iv), p11Key.keyID);
+            }
+        } catch (PKCS11Exception ex) {
+            // release session when initialization failed
+            session = token.releaseSession(session);
+            throw ex;
         }
         bytesBuffered = 0;
         padBufferLen = 0;
@@ -448,6 +456,16 @@
         return result;
     }
 
+    // reset the states to the pre-initialized values
+    private void reset() {
+        initialized = false;
+        bytesBuffered = 0;
+        padBufferLen = 0;
+        if (session != null) {
+            session = token.releaseSession(session);
+        }
+    }
+
     // see JCE spec
     protected byte[] engineUpdate(byte[] in, int inOfs, int inLen) {
         try {
@@ -566,6 +584,7 @@
                 throw (ShortBufferException)
                         (new ShortBufferException().initCause(e));
             }
+            reset();
             throw new ProviderException("update() failed", e);
         }
     }
@@ -683,6 +702,7 @@
                 throw (ShortBufferException)
                         (new ShortBufferException().initCause(e));
             }
+            reset();
             throw new ProviderException("update() failed", e);
         }
     }
@@ -729,10 +749,7 @@
             handleException(e);
             throw new ProviderException("doFinal() failed", e);
         } finally {
-            initialized = false;
-            bytesBuffered = 0;
-            padBufferLen = 0;
-            session = token.releaseSession(session);
+            reset();
         }
     }
 
@@ -806,9 +823,7 @@
             handleException(e);
             throw new ProviderException("doFinal() failed", e);
         } finally {
-            initialized = false;
-            bytesBuffered = 0;
-            session = token.releaseSession(session);
+            reset();
         }
     }
 
diff --git a/src/share/classes/sun/security/ssl/CipherSuite.java b/src/share/classes/sun/security/ssl/CipherSuite.java
index 247e34d..06351ce 100644
--- a/src/share/classes/sun/security/ssl/CipherSuite.java
+++ b/src/share/classes/sun/security/ssl/CipherSuite.java
@@ -577,14 +577,16 @@
     final static MacAlg M_SHA256  = new MacAlg("SHA256", 32);
     final static MacAlg M_SHA384  = new MacAlg("SHA384", 48);
 
-    // PRFs (PseudoRandom Function) from TLS specifications.
-    //
-    // TLS 1.1- uses a single MD5/SHA1-based PRF algorithm for generating
-    // the necessary material.
-    //
-    // In TLS 1.2+, all existing/known CipherSuites use SHA256, however
-    // new Ciphersuites (e.g. RFC 5288) can define specific PRF hash
-    // algorithms.
+    /**
+     * PRFs (PseudoRandom Function) from TLS specifications.
+     *
+     * TLS 1.1- uses a single MD5/SHA1-based PRF algorithm for generating
+     * the necessary material.
+     *
+     * In TLS 1.2+, all existing/known CipherSuites use SHA256, however
+     * new Ciphersuites (e.g. RFC 5288) can define specific PRF hash
+     * algorithms.
+     */
     static enum PRF {
 
         // PRF algorithms
@@ -862,8 +864,18 @@
         add("SSL_NULL_WITH_NULL_NULL",
                               0x0000,   1, K_NULL,       B_NULL,    F);
 
-        // Definition of the CipherSuites that are enabled by default.
-        // They are listed in preference order, most preferred first.
+        /*
+         * Definition of the CipherSuites that are enabled by default.
+         * They are listed in preference order, most preferred first, using
+         * the following criteria:
+         * 1. Prefer the stronger buld cipher, in the order of AES_256,
+         *    AES_128, RC-4, 3DES-EDE.
+         * 2. Prefer the stronger MAC algorithm, in the order of SHA384,
+         *    SHA256, SHA, MD5.
+         * 3. Prefer the better performance of key exchange and digital
+         *    signature algorithm, in the order of ECDHE-ECDSA, ECDHE-RSA,
+         *    RSA, ECDH-ECDSA, ECDH-RSA, DHE-RSA, DHE-DSS.
+         */
         int p = DEFAULT_SUITES_PRIORITY * 2;
 
         // shorten names to fit the following table cleanly.
@@ -873,170 +885,185 @@
 
         //  ID           Key Exchange   Cipher     A  obs  suprt  PRF
         //  ======       ============   =========  =  ===  =====  ========
-        add("TLS_RSA_WITH_AES_128_CBC_SHA256",
-            0x003c, --p, K_RSA,         B_AES_128, T, max, tls12, P_SHA256);
-        add("TLS_RSA_WITH_AES_256_CBC_SHA256",
-            0x003d, --p, K_RSA,         B_AES_256, T, max, tls12, P_SHA256);
-        add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256",
-            0x0040, --p, K_DHE_DSS,     B_AES_128, T, max, tls12, P_SHA256);
-        add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",
-            0x0067, --p, K_DHE_RSA,     B_AES_128, T, max, tls12, P_SHA256);
-        add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256",
-            0x006a, --p, K_DHE_DSS,     B_AES_256, T, max, tls12, P_SHA256);
-        add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",
-            0x006b, --p, K_DHE_RSA,     B_AES_256, T, max, tls12, P_SHA256);
-
-        add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
-            0xc023, --p, K_ECDHE_ECDSA, B_AES_128, T, max, tls12, P_SHA256);
         add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
             0xc024, --p, K_ECDHE_ECDSA, B_AES_256, T, max, tls12, P_SHA384);
-        add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256",
-            0xc025, --p, K_ECDH_ECDSA,  B_AES_128, T, max, tls12, P_SHA256);
-        add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384",
-            0xc026, --p, K_ECDH_ECDSA,  B_AES_256, T, max, tls12, P_SHA384);
-        add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
-            0xc027, --p, K_ECDHE_RSA,   B_AES_128, T, max, tls12, P_SHA256);
         add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
             0xc028, --p, K_ECDHE_RSA,   B_AES_256, T, max, tls12, P_SHA384);
-        add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256",
-            0xc029, --p, K_ECDH_RSA,    B_AES_128, T, max, tls12, P_SHA256);
+        add("TLS_RSA_WITH_AES_256_CBC_SHA256",
+            0x003d, --p, K_RSA,         B_AES_256, T, max, tls12, P_SHA256);
+        add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384",
+            0xc026, --p, K_ECDH_ECDSA,  B_AES_256, T, max, tls12, P_SHA384);
         add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384",
             0xc02a, --p, K_ECDH_RSA,    B_AES_256, T, max, tls12, P_SHA384);
+        add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",
+            0x006b, --p, K_DHE_RSA,     B_AES_256, T, max, tls12, P_SHA256);
+        add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256",
+            0x006a, --p, K_DHE_DSS,     B_AES_256, T, max, tls12, P_SHA256);
 
-        add("SSL_RSA_WITH_RC4_128_MD5",
-            0x0004, --p, K_RSA,         B_RC4_128, N);
-        add("SSL_RSA_WITH_RC4_128_SHA",
-            0x0005, --p, K_RSA,         B_RC4_128, N);
-        add("TLS_RSA_WITH_AES_128_CBC_SHA",
-            0x002f, --p, K_RSA,         B_AES_128, T);
-        add("TLS_RSA_WITH_AES_256_CBC_SHA",
-            0x0035, --p, K_RSA,         B_AES_256, T);
-
-        add("TLS_ECDH_ECDSA_WITH_RC4_128_SHA",
-            0xC002, --p, K_ECDH_ECDSA,  B_RC4_128, N);
-        add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",
-            0xC004, --p, K_ECDH_ECDSA,  B_AES_128, T);
-        add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",
-            0xC005, --p, K_ECDH_ECDSA,  B_AES_256, T);
-        add("TLS_ECDH_RSA_WITH_RC4_128_SHA",
-            0xC00C, --p, K_ECDH_RSA,    B_RC4_128, N);
-        add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",
-            0xC00E, --p, K_ECDH_RSA,    B_AES_128, T);
-        add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",
-            0xC00F, --p, K_ECDH_RSA,    B_AES_256, T);
-
-        add("TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
-            0xC007, --p, K_ECDHE_ECDSA, B_RC4_128, N);
-        add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
-            0xC009, --p, K_ECDHE_ECDSA, B_AES_128, T);
         add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
             0xC00A, --p, K_ECDHE_ECDSA, B_AES_256, T);
-        add("TLS_ECDHE_RSA_WITH_RC4_128_SHA",
-            0xC011, --p, K_ECDHE_RSA,   B_RC4_128, N);
-        add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
-            0xC013, --p, K_ECDHE_RSA,   B_AES_128, T);
         add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
             0xC014, --p, K_ECDHE_RSA,   B_AES_256, T);
-
-        add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
-            0x0033, --p, K_DHE_RSA,     B_AES_128, T);
+        add("TLS_RSA_WITH_AES_256_CBC_SHA",
+            0x0035, --p, K_RSA,         B_AES_256, T);
+        add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",
+            0xC005, --p, K_ECDH_ECDSA,  B_AES_256, T);
+        add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",
+            0xC00F, --p, K_ECDH_RSA,    B_AES_256, T);
         add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
             0x0039, --p, K_DHE_RSA,     B_AES_256, T);
-        add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
-            0x0032, --p, K_DHE_DSS,     B_AES_128, T);
         add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA",
             0x0038, --p, K_DHE_DSS,     B_AES_256, T);
 
+        add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
+            0xc023, --p, K_ECDHE_ECDSA, B_AES_128, T, max, tls12, P_SHA256);
+        add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
+            0xc027, --p, K_ECDHE_RSA,   B_AES_128, T, max, tls12, P_SHA256);
+        add("TLS_RSA_WITH_AES_128_CBC_SHA256",
+            0x003c, --p, K_RSA,         B_AES_128, T, max, tls12, P_SHA256);
+        add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256",
+            0xc025, --p, K_ECDH_ECDSA,  B_AES_128, T, max, tls12, P_SHA256);
+        add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256",
+            0xc029, --p, K_ECDH_RSA,    B_AES_128, T, max, tls12, P_SHA256);
+        add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",
+            0x0067, --p, K_DHE_RSA,     B_AES_128, T, max, tls12, P_SHA256);
+        add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256",
+            0x0040, --p, K_DHE_DSS,     B_AES_128, T, max, tls12, P_SHA256);
+
+        add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
+            0xC009, --p, K_ECDHE_ECDSA, B_AES_128, T);
+        add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
+            0xC013, --p, K_ECDHE_RSA,   B_AES_128, T);
+        add("TLS_RSA_WITH_AES_128_CBC_SHA",
+            0x002f, --p, K_RSA,         B_AES_128, T);
+        add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",
+            0xC004, --p, K_ECDH_ECDSA,  B_AES_128, T);
+        add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",
+            0xC00E, --p, K_ECDH_RSA,    B_AES_128, T);
+        add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
+            0x0033, --p, K_DHE_RSA,     B_AES_128, T);
+        add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
+            0x0032, --p, K_DHE_DSS,     B_AES_128, T);
+
+        add("TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
+            0xC007, --p, K_ECDHE_ECDSA, B_RC4_128, N);
+        add("TLS_ECDHE_RSA_WITH_RC4_128_SHA",
+            0xC011, --p, K_ECDHE_RSA,   B_RC4_128, N);
+        add("SSL_RSA_WITH_RC4_128_SHA",
+            0x0005, --p, K_RSA,         B_RC4_128, N);
+        add("TLS_ECDH_ECDSA_WITH_RC4_128_SHA",
+            0xC002, --p, K_ECDH_ECDSA,  B_RC4_128, N);
+        add("TLS_ECDH_RSA_WITH_RC4_128_SHA",
+            0xC00C, --p, K_ECDH_RSA,    B_RC4_128, N);
+
+        add("TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
+            0xC008, --p, K_ECDHE_ECDSA, B_3DES,    T);
+        add("TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
+            0xC012, --p, K_ECDHE_RSA,   B_3DES,    T);
         add("SSL_RSA_WITH_3DES_EDE_CBC_SHA",
             0x000a, --p, K_RSA,         B_3DES,    T);
         add("TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",
             0xC003, --p, K_ECDH_ECDSA,  B_3DES,    T);
         add("TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",
             0xC00D, --p, K_ECDH_RSA,    B_3DES,    T);
-        add("TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
-            0xC008, --p, K_ECDHE_ECDSA, B_3DES,    T);
-        add("TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
-            0xC012, --p, K_ECDHE_RSA,   B_3DES,    T);
         add("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
             0x0016, --p, K_DHE_RSA,     B_3DES,    T);
         add("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA",
             0x0013, --p, K_DHE_DSS,     B_3DES,    N);
 
+        add("SSL_RSA_WITH_RC4_128_MD5",
+            0x0004, --p, K_RSA,         B_RC4_128, N);
+
         // Renegotiation protection request Signalling Cipher Suite Value (SCSV)
         add("TLS_EMPTY_RENEGOTIATION_INFO_SCSV",
             0x00ff, --p, K_SCSV,        B_NULL,    T);
 
-        // Definition of the CipherSuites that are supported but not enabled
-        // by default.
-        // They are listed in preference order, preferred first.
+        /*
+         * Definition of the CipherSuites that are supported but not enabled
+         * by default.
+         * They are listed in preference order, preferred first, using the
+         * following criteria:
+         * 1. CipherSuites for KRB5 need additional KRB5 service
+         *    configuration, and these suites are not common in practice,
+         *    so we put KRB5 based cipher suites at the end of the supported
+         *    list.
+         * 2. If a cipher suite has been obsoleted, we put it at the end of
+         *    the list.
+         * 3. Prefer the stronger bulk cipher, in the order of AES_256,
+         *    AES_128, RC-4, 3DES-EDE, DES, RC4_40, DES40, NULL.
+         * 4. Prefer the stronger MAC algorithm, in the order of SHA384,
+         *    SHA256, SHA, MD5.
+         * 5. Prefer the better performance of key exchange and digital
+         *    signature algorithm, in the order of ECDHE-ECDSA, ECDHE-RSA,
+         *    RSA, ECDH-ECDSA, ECDH-RSA, DHE-RSA, DHE-DSS, anonymous.
+         */
         p = DEFAULT_SUITES_PRIORITY;
 
-        // weak single-DES cipher suites
+        add("TLS_DH_anon_WITH_AES_256_CBC_SHA256",
+            0x006d, --p, K_DH_ANON,     B_AES_256, N, max, tls12, P_SHA256);
+        add("TLS_ECDH_anon_WITH_AES_256_CBC_SHA",
+            0xC019, --p, K_ECDH_ANON,   B_AES_256, T);
+        add("TLS_DH_anon_WITH_AES_256_CBC_SHA",
+            0x003a, --p, K_DH_ANON,     B_AES_256, N);
+
+        add("TLS_DH_anon_WITH_AES_128_CBC_SHA256",
+            0x006c, --p, K_DH_ANON,     B_AES_128, N, max, tls12, P_SHA256);
+        add("TLS_ECDH_anon_WITH_AES_128_CBC_SHA",
+            0xC018, --p, K_ECDH_ANON,   B_AES_128, T);
+        add("TLS_DH_anon_WITH_AES_128_CBC_SHA",
+            0x0034, --p, K_DH_ANON,     B_AES_128, N);
+
+        add("TLS_ECDH_anon_WITH_RC4_128_SHA",
+            0xC016, --p, K_ECDH_ANON,   B_RC4_128, N);
+        add("SSL_DH_anon_WITH_RC4_128_MD5",
+            0x0018, --p, K_DH_ANON,     B_RC4_128, N);
+
+        add("TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA",
+            0xC017, --p, K_ECDH_ANON,   B_3DES,    T);
+        add("SSL_DH_anon_WITH_3DES_EDE_CBC_SHA",
+            0x001b, --p, K_DH_ANON,     B_3DES,    N);
+
+        add("TLS_RSA_WITH_NULL_SHA256",
+            0x003b, --p, K_RSA,         B_NULL,    N, max, tls12, P_SHA256);
+        add("TLS_ECDHE_ECDSA_WITH_NULL_SHA",
+            0xC006, --p, K_ECDHE_ECDSA, B_NULL,    N);
+        add("TLS_ECDHE_RSA_WITH_NULL_SHA",
+            0xC010, --p, K_ECDHE_RSA,   B_NULL,    N);
+        add("SSL_RSA_WITH_NULL_SHA",
+            0x0002, --p, K_RSA,         B_NULL,    N);
+        add("TLS_ECDH_ECDSA_WITH_NULL_SHA",
+            0xC001, --p, K_ECDH_ECDSA,  B_NULL,    N);
+        add("TLS_ECDH_RSA_WITH_NULL_SHA",
+            0xC00B, --p, K_ECDH_RSA,    B_NULL,    N);
+        add("TLS_ECDH_anon_WITH_NULL_SHA",
+            0xC015, --p, K_ECDH_ANON,   B_NULL,    N);
+        add("SSL_RSA_WITH_NULL_MD5",
+            0x0001, --p, K_RSA,         B_NULL,    N);
+
+        // weak cipher suites obsoleted in TLS 1.2
         add("SSL_RSA_WITH_DES_CBC_SHA",
             0x0009, --p, K_RSA,         B_DES,     N, tls12);
         add("SSL_DHE_RSA_WITH_DES_CBC_SHA",
             0x0015, --p, K_DHE_RSA,     B_DES,     N, tls12);
         add("SSL_DHE_DSS_WITH_DES_CBC_SHA",
             0x0012, --p, K_DHE_DSS,     B_DES,     N, tls12);
-
-        // Anonymous key exchange and the NULL ciphers
-        add("SSL_RSA_WITH_NULL_MD5",
-            0x0001, --p, K_RSA,         B_NULL,    N);
-        add("SSL_RSA_WITH_NULL_SHA",
-            0x0002, --p, K_RSA,         B_NULL,    N);
-        add("TLS_RSA_WITH_NULL_SHA256",
-            0x003b, --p, K_RSA,         B_NULL,    N, max, tls12, P_SHA256);
-
-        add("TLS_ECDH_ECDSA_WITH_NULL_SHA",
-            0xC001, --p, K_ECDH_ECDSA,  B_NULL,    N);
-        add("TLS_ECDH_RSA_WITH_NULL_SHA",
-            0xC00B, --p, K_ECDH_RSA,    B_NULL,    N);
-        add("TLS_ECDHE_ECDSA_WITH_NULL_SHA",
-            0xC006, --p, K_ECDHE_ECDSA, B_NULL,    N);
-        add("TLS_ECDHE_RSA_WITH_NULL_SHA",
-            0xC010, --p, K_ECDHE_RSA,   B_NULL,    N);
-
-        add("SSL_DH_anon_WITH_RC4_128_MD5",
-            0x0018, --p, K_DH_ANON,     B_RC4_128, N);
-        add("TLS_DH_anon_WITH_AES_128_CBC_SHA",
-            0x0034, --p, K_DH_ANON,     B_AES_128, N);
-        add("TLS_DH_anon_WITH_AES_256_CBC_SHA",
-            0x003a, --p, K_DH_ANON,     B_AES_256, N);
-        add("SSL_DH_anon_WITH_3DES_EDE_CBC_SHA",
-            0x001b, --p, K_DH_ANON,     B_3DES,    N);
         add("SSL_DH_anon_WITH_DES_CBC_SHA",
             0x001a, --p, K_DH_ANON,     B_DES,     N, tls12);
 
-        add("TLS_DH_anon_WITH_AES_128_CBC_SHA256",
-            0x006c, --p, K_DH_ANON,     B_AES_128, N, max, tls12, P_SHA256);
-        add("TLS_DH_anon_WITH_AES_256_CBC_SHA256",
-            0x006d, --p, K_DH_ANON,     B_AES_256, N, max, tls12, P_SHA256);
-
-        add("TLS_ECDH_anon_WITH_RC4_128_SHA",
-            0xC016, --p, K_ECDH_ANON,   B_RC4_128, N);
-        add("TLS_ECDH_anon_WITH_AES_128_CBC_SHA",
-            0xC018, --p, K_ECDH_ANON,   B_AES_128, T);
-        add("TLS_ECDH_anon_WITH_AES_256_CBC_SHA",
-            0xC019, --p, K_ECDH_ANON,   B_AES_256, T);
-        add("TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA",
-            0xC017, --p, K_ECDH_ANON,   B_3DES,    T);
-
-        add("SSL_DH_anon_EXPORT_WITH_RC4_40_MD5",
-            0x0017, --p, K_DH_ANON,     B_RC4_40,  N, tls11);
-        add("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA",
-            0x0019, --p, K_DH_ANON,     B_DES_40,  N, tls11);
-
-        add("TLS_ECDH_anon_WITH_NULL_SHA",
-            0xC015, --p, K_ECDH_ANON,   B_NULL,    N);
-
+        // weak cipher suites obsoleted in TLS 1.1
         add("SSL_RSA_EXPORT_WITH_RC4_40_MD5",
             0x0003, --p, K_RSA_EXPORT,  B_RC4_40,  N, tls11);
+        add("SSL_DH_anon_EXPORT_WITH_RC4_40_MD5",
+            0x0017, --p, K_DH_ANON,     B_RC4_40,  N, tls11);
+
         add("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
             0x0008, --p, K_RSA_EXPORT,  B_DES_40,  N, tls11);
         add("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
             0x0014, --p, K_DHE_RSA,     B_DES_40,  N, tls11);
         add("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA",
             0x0011, --p, K_DHE_DSS,     B_DES_40,  N, tls11);
+        add("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA",
+            0x0019, --p, K_DH_ANON,     B_DES_40,  N, tls11);
 
         // Supported Kerberos ciphersuites from RFC2712
         add("TLS_KRB5_WITH_RC4_128_SHA",
diff --git a/src/share/classes/sun/security/ssl/ClientHandshaker.java b/src/share/classes/sun/security/ssl/ClientHandshaker.java
index af835db..81cdfd1 100644
--- a/src/share/classes/sun/security/ssl/ClientHandshaker.java
+++ b/src/share/classes/sun/security/ssl/ClientHandshaker.java
@@ -381,8 +381,7 @@
                     mesgVersion);
         }
 
-        handshakeHash.protocolDetermined(
-            mesgVersion.v >= ProtocolVersion.TLS12.v);
+        handshakeHash.protocolDetermined(mesgVersion);
 
         // Set protocolVersion and propagate to SSLSocket and the
         // Handshake streams
@@ -1223,7 +1222,7 @@
         // not follow the spec that HandshakeHash.reset() can be only be
         // called before protocolDetermined.
         // if (maxProtocolVersion.v < ProtocolVersion.TLS12.v) {
-        //     handshakeHash.protocolDetermined(false);
+        //     handshakeHash.protocolDetermined(maxProtocolVersion);
         // }
 
         // create the ClientHello message
diff --git a/src/share/classes/sun/security/ssl/HandshakeHash.java b/src/share/classes/sun/security/ssl/HandshakeHash.java
index 86ebb51..ffb8f32 100644
--- a/src/share/classes/sun/security/ssl/HandshakeHash.java
+++ b/src/share/classes/sun/security/ssl/HandshakeHash.java
@@ -49,27 +49,27 @@
  *
  * You need to obey these conventions when using this class:
  *
- * 1. protocolDetermined(boolean isTLS12) should be called when the negotiated
+ * 1. protocolDetermined(version) should be called when the negotiated
  * protocol version is determined.
  *
  * 2. Before protocolDetermined() is called, only update(), reset(),
  * restrictCertificateVerifyAlgs(), setFinishedAlg(), and
  * setCertificateVerifyAlg() can be called.
  *
- * 3. After protocolDetermined(*) is called. reset() cannot be called.
+ * 3. After protocolDetermined() is called, reset() cannot be called.
  *
- * 4. After protocolDetermined(false) is called, getFinishedHash() and
- * getCertificateVerifyHash() cannot be called. After protocolDetermined(true)
- * is called, getMD5Clone() and getSHAClone() cannot be called.
+ * 4. After protocolDetermined() is called, if the version is pre-TLS 1.2,
+ * getFinishedHash() and getCertificateVerifyHash() cannot be called. Otherwise,
+ * getMD5Clone() and getSHAClone() cannot be called.
  *
  * 5. getMD5Clone() and getSHAClone() can only be called after
- * protocolDetermined(false) is called.
+ * protocolDetermined() is called and version is pre-TLS 1.2.
  *
  * 6. getFinishedHash() and getCertificateVerifyHash() can only be called after
- * all protocolDetermined(true), setCertificateVerifyAlg() and setFinishedAlg()
- * have been called. If a CertificateVerify message is to be used, call
- * setCertificateVerifyAlg() with the hash algorithm as the argument.
- * Otherwise, you still must call setCertificateVerifyAlg(null) before
+ * all protocolDetermined(), setCertificateVerifyAlg() and setFinishedAlg()
+ * have been called and the version is TLS 1.2. If a CertificateVerify message
+ * is to be used, call setCertificateVerifyAlg() with the hash algorithm as the
+ * argument. Otherwise, you still must call setCertificateVerifyAlg(null) before
  * calculating any hash value.
  *
  * Suggestions: Call protocolDetermined(), restrictCertificateVerifyAlgs(),
@@ -78,6 +78,7 @@
  * Example:
  * <pre>
  * HandshakeHash hh = new HandshakeHash(...)
+ * hh.protocolDetermined(ProtocolVersion.TLS12);
  * hh.update(clientHelloBytes);
  * hh.setFinishedAlg("SHA-256");
  * hh.update(serverHelloBytes);
@@ -161,12 +162,12 @@
     }
 
 
-    void protocolDetermined(boolean isTLS12) {
+    void protocolDetermined(ProtocolVersion pv) {
 
         // Do not set again, will ignore
         if (version != -1) return;
 
-        version = isTLS12 ? 2 : 1;
+        version = pv.compareTo(ProtocolVersion.TLS12) >= 0 ? 2 : 1;
         switch (version) {
             case 1:
                 // initiate md5, sha and call update on saved array
@@ -310,91 +311,6 @@
             throw new Error("BAD");
         }
     }
-
-    ////////////////////////////////////////////////////////////////
-    // TEST
-    ////////////////////////////////////////////////////////////////
-
-    public static void main(String[] args) throws Exception {
-        Test t = new Test();
-        t.test(null, "SHA-256");
-        t.test("", "SHA-256");
-        t.test("SHA-1", "SHA-256");
-        t.test("SHA-256", "SHA-256");
-        t.test("SHA-384", "SHA-256");
-        t.test("SHA-512", "SHA-256");
-        t.testSame("sha", "SHA-1");
-        t.testSame("SHA", "SHA-1");
-        t.testSame("SHA1", "SHA-1");
-        t.testSame("SHA-1", "SHA-1");
-        t.testSame("SHA256", "SHA-256");
-        t.testSame("SHA-256", "SHA-256");
-    }
-
-    static class Test {
-        void update(HandshakeHash hh, String s) {
-            hh.update(s.getBytes(), 0, s.length());
-        }
-        static byte[] digest(String alg, String data) throws Exception {
-            return MessageDigest.getInstance(alg).digest(data.getBytes());
-        }
-        static void equals(byte[] b1, byte[] b2) {
-            if (!Arrays.equals(b1, b2)) {
-                throw new RuntimeException("Bad");
-            }
-        }
-        void testSame(String a, String a2) {
-            System.out.println("testSame: " + a + " " + a2);
-            if (!HandshakeHash.normalizeAlgName(a).equals(a2)) {
-                throw new RuntimeException("Bad");
-            }
-        }
-        /**
-         * Special convention: when it's certain that CV will not be used at the
-         * very beginning, use null as cvAlg. If known at a late stage, use "".
-         */
-        void test(String cvAlg, String finAlg) throws Exception {
-            System.out.println("test: " + cvAlg + " " + finAlg);
-            byte[] cv = null, f1, f2;
-            HandshakeHash hh = new HandshakeHash(true, true, null);
-            if (cvAlg == null) {
-                hh.setCertificateVerifyAlg(cvAlg);
-            }
-
-            update(hh, "ClientHello,");
-            hh.reset();
-            update(hh, "ClientHellov2,");
-            hh.setFinishedAlg(finAlg);
-
-            // Useless calls
-            hh.setFinishedAlg("SHA-1");
-            hh.setFinishedAlg("SHA-512");
-
-            update(hh, "More,");
-            if (cvAlg != null) {
-                if (cvAlg.isEmpty()) cvAlg = null;
-                hh.setCertificateVerifyAlg(cvAlg);
-            }
-
-            // Useless calls
-            hh.setCertificateVerifyAlg("SHA-1");
-            hh.setCertificateVerifyAlg(null);
-
-            hh.protocolDetermined(true);
-
-            if (cvAlg != null) {
-                cv = hh.getAllHandshakeMessages();
-                equals(cv, "ClientHellov2,More,".getBytes());
-            }
-
-            update(hh, "FIN1,");
-            f1 = hh.getFinishedHash();
-            equals(f1, digest(finAlg, "ClientHellov2,More,FIN1,"));
-            update(hh, "FIN2,");
-            f2 = hh.getFinishedHash();
-            equals(f2, digest(finAlg, "ClientHellov2,More,FIN1,FIN2,"));
-        }
-    }
 }
 
 /**
diff --git a/src/share/classes/sun/security/ssl/ServerHandshaker.java b/src/share/classes/sun/security/ssl/ServerHandshaker.java
index c393314..ff1c8d7 100644
--- a/src/share/classes/sun/security/ssl/ServerHandshaker.java
+++ b/src/share/classes/sun/security/ssl/ServerHandshaker.java
@@ -424,8 +424,7 @@
                 " not enabled or not supported");
         }
 
-        handshakeHash.protocolDetermined(
-            selectedVersion.v >= ProtocolVersion.TLS12.v);
+        handshakeHash.protocolDetermined(selectedVersion);
         setVersion(selectedVersion);
 
         m1.protocolVersion = protocolVersion;
diff --git a/src/share/classes/sun/tools/jstat/resources/jstat_options b/src/share/classes/sun/tools/jstat/resources/jstat_options
index c5ed3d4..14a2d05 100644
--- a/src/share/classes/sun/tools/jstat/resources/jstat_options
+++ b/src/share/classes/sun/tools/jstat/resources/jstat_options
@@ -589,7 +589,7 @@
   }
   column {
     header "^S0CMX^"	/* Survivor 0 Space Capacity - Maximum */
-    data sun.gc.generation.0.space.1.capacity
+    data sun.gc.generation.0.space.1.maxCapacity
     scale K
     align right
     width 8
@@ -597,7 +597,7 @@
   }
   column {
     header "^S0C^"	/* Survivor 0 Space Capacity - Current */
-    data sun.gc.generation.0.space.1.maxCapacity
+    data sun.gc.generation.0.space.1.capacity
     scale K
     align right
     width 8
diff --git a/src/share/classes/sun/util/logging/PlatformLogger.java b/src/share/classes/sun/util/logging/PlatformLogger.java
index 9629a66..ae12554 100644
--- a/src/share/classes/sun/util/logging/PlatformLogger.java
+++ b/src/share/classes/sun/util/logging/PlatformLogger.java
@@ -113,7 +113,7 @@
 
     // Table of known loggers.  Maps names to PlatformLoggers.
     private static Map<String,WeakReference<PlatformLogger>> loggers =
-        new HashMap<String,WeakReference<PlatformLogger>>();
+        new HashMap<>();
 
     /**
      * Returns a PlatformLogger of a given name.
@@ -126,7 +126,7 @@
         }
         if (log == null) {
             log = new PlatformLogger(name);
-            loggers.put(name, new WeakReference<PlatformLogger>(log));
+            loggers.put(name, new WeakReference<>(log));
         }
         return log;
     }
@@ -488,7 +488,7 @@
      */
     static class JavaLogger extends LoggerProxy {
         private static final Map<Integer, Object> levelObjects =
-            new HashMap<Integer, Object>();
+            new HashMap<>();
 
         static {
             if (LoggingSupport.isAvailable()) {
diff --git a/src/share/demo/jvmti/heapTracker/heapTracker.c b/src/share/demo/jvmti/heapTracker/heapTracker.c
index 8cc294c..4704c5b 100644
--- a/src/share/demo/jvmti/heapTracker/heapTracker.c
+++ b/src/share/demo/jvmti/heapTracker/heapTracker.c
@@ -340,7 +340,7 @@
 }
 
 /* Java Native Method for Object.<init> */
-static void
+static void JNICALL
 HEAP_TRACKER_native_newobj(JNIEnv *env, jclass klass, jthread thread, jobject o)
 {
     TraceInfo *tinfo;
@@ -353,7 +353,7 @@
 }
 
 /* Java Native Method for newarray */
-static void
+static void JNICALL
 HEAP_TRACKER_native_newarr(JNIEnv *env, jclass klass, jthread thread, jobject a)
 {
     TraceInfo *tinfo;
diff --git a/src/share/native/sun/awt/splashscreen/splashscreen_gfx_impl.h b/src/share/native/sun/awt/splashscreen/splashscreen_gfx_impl.h
index f2f367c..a0fd446 100644
--- a/src/share/native/sun/awt/splashscreen/splashscreen_gfx_impl.h
+++ b/src/share/native/sun/awt/splashscreen/splashscreen_gfx_impl.h
@@ -88,27 +88,18 @@
 /*      blend (lerp between) two rgb quads
         src and dst alpha is ignored
         the algorithm: src*alpha+dst*(1-alpha)=(src-dst)*alpha+dst, rb and g are done separately
-        it's possible to verify that it's almost accurate indeed */
-
+*/
 INLINE rgbquad_t
 blendRGB(rgbquad_t dst, rgbquad_t src, rgbquad_t alpha)
 {
-    const rgbquad_t dstrb = dst & 0xFF00FF;
-    const rgbquad_t dstg = dst & 0xFF00;
-    const rgbquad_t srcrb = src & 0xFF00FF;
-    const rgbquad_t srcg = src & 0xFF00;
+    const rgbquad_t a = alpha;
+    const rgbquad_t a1 = 0xFF - alpha;
 
-    rgbquad_t drb = srcrb - dstrb;
-    rgbquad_t dg = srcg - dstg;
-
-    alpha += 1;
-
-    drb *= alpha;
-    dg *= alpha;
-    drb >>= 8;
-    dg >>= 8;
-
-    return ((drb + dstrb) & 0xFF00FF) | ((dg + dstg) & 0xFF00);
+    return MAKE_QUAD(
+        (rgbquad_t)((QUAD_RED(src) * a + QUAD_RED(dst) * a1) / 0xFF),
+        (rgbquad_t)((QUAD_GREEN(src) * a + QUAD_GREEN(dst) * a1) / 0xFF),
+        (rgbquad_t)((QUAD_BLUE(src) * a + QUAD_BLUE(dst) * a1) / 0xFF),
+        0);
 }
 
 /*      scales rgb quad by alpha. basically similar to what's above. src alpha is retained.
diff --git a/src/solaris/classes/java/lang/ProcessEnvironment.java b/src/solaris/classes/java/lang/ProcessEnvironment.java
index a6e4c4a..a08a291 100644
--- a/src/solaris/classes/java/lang/ProcessEnvironment.java
+++ b/src/solaris/classes/java/lang/ProcessEnvironment.java
@@ -68,7 +68,7 @@
         // We cache the C environment.  This means that subsequent calls
         // to putenv/setenv from C will not be visible from Java code.
         byte[][] environ = environ();
-        theEnvironment = new HashMap<Variable,Value>(environ.length/2 + 3);
+        theEnvironment = new HashMap<>(environ.length/2 + 3);
         // Read environment variables back to front,
         // so that earlier variables override later ones.
         for (int i = environ.length-1; i > 0; i-=2)
diff --git a/src/solaris/classes/java/util/prefs/FileSystemPreferences.java b/src/solaris/classes/java/util/prefs/FileSystemPreferences.java
index 1982932..32e4b03 100644
--- a/src/solaris/classes/java/util/prefs/FileSystemPreferences.java
+++ b/src/solaris/classes/java/util/prefs/FileSystemPreferences.java
@@ -354,7 +354,7 @@
      * log against that map.  The resulting map is then written back
      * to the disk.
      */
-    final List<Change> changeLog = new ArrayList<Change>();
+    final List<Change> changeLog = new ArrayList<>();
 
     /**
      * Represents a change to a preference.
@@ -507,7 +507,7 @@
         });
         if (newNode) {
             // These 2 things guarantee node will get wrtten at next flush/sync
-            prefsCache = new TreeMap<String, String>();
+            prefsCache = new TreeMap<>();
             nodeCreate = new NodeCreate();
             changeLog.add(nodeCreate);
         }
@@ -550,7 +550,7 @@
             loadCache();
         } catch(Exception e) {
             // assert lastSyncTime == 0;
-            prefsCache = new TreeMap<String, String>();
+            prefsCache = new TreeMap<>();
         }
     }
 
@@ -567,7 +567,7 @@
             AccessController.doPrivileged(
                 new PrivilegedExceptionAction<Void>() {
                 public Void run() throws BackingStoreException {
-                    Map<String, String> m = new TreeMap<String, String>();
+                    Map<String, String> m = new TreeMap<>();
                     long newLastSyncTime = 0;
                     try {
                         newLastSyncTime = prefsFile.lastModified();
@@ -581,7 +581,7 @@
                             prefsFile.renameTo( new File(
                                                     prefsFile.getParentFile(),
                                                   "IncorrectFormatPrefs.xml"));
-                            m = new TreeMap<String, String>();
+                            m = new TreeMap<>();
                         } else if (e instanceof FileNotFoundException) {
                         getLogger().warning("Prefs file removed in background "
                                            + prefsFile.getPath());
@@ -646,7 +646,7 @@
         return AccessController.doPrivileged(
             new PrivilegedAction<String[]>() {
                 public String[] run() {
-                    List<String> result = new ArrayList<String>();
+                    List<String> result = new ArrayList<>();
                     File[] dirContents = dir.listFiles();
                     if (dirContents != null) {
                         for (int i = 0; i < dirContents.length; i++)
@@ -794,7 +794,7 @@
         } else if (lastSyncTime != 0 && !dir.exists()) {
             // This node was removed in the background.  Playback any changes
             // against a virgin (empty) Map.
-            prefsCache = new TreeMap<String, String>();
+            prefsCache = new TreeMap<>();
             replayChanges();
         }
         if (!changeLog.isEmpty()) {
diff --git a/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_CommonUtils.c b/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_CommonUtils.c
index 3128efe..73ec256 100644
--- a/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_CommonUtils.c
+++ b/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_CommonUtils.c
@@ -137,41 +137,43 @@
         file = fopen(ALSA_VERSION_PROC_FILE, "r");
         ALSAVersionString[0] = 0;
         if (file) {
-            fgets(ALSAVersionString, ALSAVersionString_LENGTH, file);
-            // parse for version number
-            totalLen = strlen(ALSAVersionString);
-            inVersionString = FALSE;
-            len = 0;
-            curr = 0;
-            while (curr < totalLen) {
-                if (!inVersionString) {
-                    // is this char the beginning of a version string ?
-                    if (ALSAVersionString[curr] >= '0'
-                        && ALSAVersionString[curr] <= '9') {
-                        inVersionString = TRUE;
+            if (NULL != fgets(ALSAVersionString, ALSAVersionString_LENGTH, file)) {
+                // parse for version number
+                totalLen = strlen(ALSAVersionString);
+                inVersionString = FALSE;
+                len = 0;
+                curr = 0;
+                while (curr < totalLen) {
+                    if (!inVersionString) {
+                        // is this char the beginning of a version string ?
+                        if (ALSAVersionString[curr] >= '0'
+                            && ALSAVersionString[curr] <= '9') {
+                            inVersionString = TRUE;
+                        }
                     }
+                    if (inVersionString) {
+                        // the version string ends with white space
+                        if (ALSAVersionString[curr] <= 32) {
+                            break;
+                        }
+                        if (curr != len) {
+                            // copy this char to the beginning of the string
+                            ALSAVersionString[len] = ALSAVersionString[curr];
+                        }
+                        len++;
+                    }
+                    curr++;
                 }
-                if (inVersionString) {
-                    // the version string ends with white space
-                    if (ALSAVersionString[curr] <= 32) {
-                        break;
-                    }
-                    if (curr != len) {
-                        // copy this char to the beginning of the string
-                        ALSAVersionString[len] = ALSAVersionString[curr];
-                    }
-                    len++;
+                // remove trailing dots
+                while ((len > 0) && (ALSAVersionString[len - 1] == '.')) {
+                    len--;
                 }
-                curr++;
+                // null terminate
+                ALSAVersionString[len] = 0;
             }
-            // remove trailing dots
-            while ((len > 0) && (ALSAVersionString[len - 1] == '.')) {
-                len--;
-            }
-            // null terminate
-            ALSAVersionString[len] = 0;
+            fclose(file);
+            hasGottenALSAVersion = TRUE;
         }
-        hasGottenALSAVersion = TRUE;
     }
     strncpy(buffer, ALSAVersionString, len);
 }
diff --git a/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_MidiIn.c b/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_MidiIn.c
index a2277bd..db4a30c 100644
--- a/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_MidiIn.c
+++ b/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_MidiIn.c
@@ -32,6 +32,9 @@
 #include <alsa/asoundlib.h>
 #include "PlatformMidi.h"
 #include "PLATFORM_API_LinuxOS_ALSA_MidiUtils.h"
+#if defined(i586)
+#include <sys/utsname.h>
+#endif
 
 /*
  * Helper methods
@@ -73,9 +76,38 @@
     return (char*) getErrorStr(err);
 }
 
-
 INT32 MIDI_IN_GetNumDevices() {
+/* Workaround for 6842956: 32bit app on 64bit linux
+ * gets assertion failure trying to open midiIn ports.
+ * Untill the issue is fixed in ALSA
+ * (https://bugtrack.alsa-project.org/alsa-bug/view.php?id=4807)
+ * report no midi in devices in the configuration.
+ */
+#if defined(i586)
+    static int jre32onlinux64 = -1;
+    if (jre32onlinux64 < 0) {
+        jre32onlinux64 = 0;
+        /* The workaround may be disabled setting "JAVASOUND_ENABLE_MIDIIN"
+         * environment variable.
+         */
+        if (getenv("JAVASOUND_ENABLE_MIDIIN") == NULL) {
+            struct utsname u;
+            jre32onlinux64 = 0;
+            if (uname(&u) == 0) {
+                if (strstr(u.machine, "64") != NULL) {
+                    TRACE0("jre32 on linux64 detected - report no midiIn devices\n");
+                    jre32onlinux64 = 1;
+                }
+            }
+        }
+    }
+    if (jre32onlinux64) {
+        return 0;
+    }
+#endif
+
     TRACE0("MIDI_IN_GetNumDevices()\n");
+
     return getMidiDeviceCount(SND_RAWMIDI_STREAM_INPUT);
 }
 
diff --git a/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_MidiUtils.c b/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_MidiUtils.c
index 74af23e..7d2ac11 100644
--- a/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_MidiUtils.c
+++ b/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_MidiUtils.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -372,7 +372,7 @@
     snd_rawmidi_t* native_handle;
     snd_midi_event_t* event_parser = NULL;
     int err;
-    UINT32 deviceID;
+    UINT32 deviceID = 0;
     char devicename[100];
 #ifdef ALSA_MIDI_USE_PLUGHW
     int usePlugHw = 1;
diff --git a/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_PCM.c b/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_PCM.c
index 58ca8ab..fb2ba3c 100644
--- a/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_PCM.c
+++ b/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_PCM.c
@@ -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
@@ -127,7 +127,7 @@
     int ret;
     int sampleSizeInBytes, significantBits, isSigned, isBigEndian, enc;
     int origSampleSizeInBytes, origSignificantBits;
-    int channels, minChannels, maxChannels;
+    unsigned int channels, minChannels, maxChannels;
     int rate, bitIndex;
 
     for (bitIndex = 0; bitIndex <= MAX_BIT_INDEX; bitIndex++) handledBits[bitIndex] = FALSE;
@@ -152,7 +152,6 @@
             }
         }
         snd_pcm_hw_params_get_format_mask(hwParams, formatMask);
-#ifdef ALSA_PCM_NEW_HW_PARAMS_API
         if (ret == 0) {
             ret = snd_pcm_hw_params_get_channels_min(hwParams, &minChannels);
             if (ret != 0) {
@@ -165,13 +164,6 @@
                 ERROR1("snd_pcm_hw_params_get_channels_max returned error %d\n", ret);
             }
         }
-#else
-        minChannels = snd_pcm_hw_params_get_channels_min(hwParams);
-        maxChannels = snd_pcm_hw_params_get_channels_max(hwParams);
-        if (minChannels > maxChannels) {
-            ERROR2("MinChannels=%d, maxChannels=%d\n", minChannels, maxChannels);
-        }
-#endif
 
         // since we queried the hw: device, for many soundcards, it will only
         // report the maximum number of channels (which is the only way to talk
@@ -222,7 +214,7 @@
                                 } else {
                                     for (channels = minChannels; channels <= maxChannels; channels++) {
                                         DAUDIO_AddAudioFormat(creator, significantBits,
-                                                              (channels < 0)?-1:(sampleSizeInBytes * channels),
+                                                              sampleSizeInBytes * channels,
                                                               channels, rate,
                                                               enc, isSigned, isBigEndian);
                                     }
@@ -254,7 +246,7 @@
     snd_pcm_sw_params_t* swParams;
     int bufferSizeInBytes;
     int frameSize; // storage size in Bytes
-    int periods;
+    unsigned int periods;
     snd_pcm_uframes_t periodSize;
 #ifdef GET_POSITION_METHOD2
     // to be used exclusively by getBytePosition!
@@ -305,8 +297,8 @@
                 int channels,
                 int bufferSizeInFrames,
                 snd_pcm_format_t format) {
-    unsigned int rrate;
-    int ret, dir, periods, periodTime;
+    unsigned int rrate, periodTime, periods;
+    int ret, dir;
     snd_pcm_uframes_t alsaBufferSizeInFrames = (snd_pcm_uframes_t) bufferSizeInFrames;
 
     /* choose all parameters */
@@ -335,12 +327,8 @@
     }
     /* set the stream rate */
     rrate = (int) (sampleRate + 0.5f);
-#ifdef ALSA_PCM_NEW_HW_PARAMS_API
     dir = 0;
     ret = snd_pcm_hw_params_set_rate_near(info->handle, info->hwParams, &rrate, &dir);
-#else
-    ret = snd_pcm_hw_params_set_rate_near(info->handle, info->hwParams, rrate, 0);
-#endif
     if (ret < 0) {
         ERROR2("Rate %dHz not available for playback: %s\n", (int) (sampleRate+0.5f), snd_strerror(ret));
         return FALSE;
@@ -350,12 +338,7 @@
         return FALSE;
     }
     /* set the buffer time */
-#ifdef ALSA_PCM_NEW_HW_PARAMS_API
-
     ret = snd_pcm_hw_params_set_buffer_size_near(info->handle, info->hwParams, &alsaBufferSizeInFrames);
-#else
-    ret = snd_pcm_hw_params_set_buffer_size_near(info->handle, info->hwParams, alsaBufferSizeInFrames);
-#endif
     if (ret < 0) {
         ERROR2("Unable to set buffer size to %d frames: %s\n",
                (int) alsaBufferSizeInFrames, snd_strerror(ret));
@@ -366,12 +349,7 @@
     if (bufferSizeInFrames > 1024) {
         dir = 0;
         periodTime = DEFAULT_PERIOD_TIME;
-#ifdef ALSA_PCM_NEW_HW_PARAMS_API
         ret = snd_pcm_hw_params_set_period_time_near(info->handle, info->hwParams, &periodTime, &dir);
-#else
-        periodTime = snd_pcm_hw_params_set_period_time_near(info->handle, info->hwParams, periodTime, &dir);
-        ret = periodTime;
-#endif
         if (ret < 0) {
             ERROR2("Unable to set period time to %d: %s\n", DEFAULT_PERIOD_TIME, snd_strerror(ret));
             return FALSE;
@@ -380,12 +358,7 @@
         /* set the period count for very small buffer sizes to 2 */
         dir = 0;
         periods = 2;
-#ifdef ALSA_PCM_NEW_HW_PARAMS_API
         ret = snd_pcm_hw_params_set_periods_near(info->handle, info->hwParams, &periods, &dir);
-#else
-        periods = snd_pcm_hw_params_set_periods_near(info->handle, info->hwParams, periods, &dir);
-        ret = periods;
-#endif
         if (ret < 0) {
             ERROR2("Unable to set period count to %d: %s\n", /*periods*/ 2, snd_strerror(ret));
             return FALSE;
@@ -421,12 +394,6 @@
         ERROR1("Unable to set avail min for playback: %s\n", snd_strerror(ret));
         return FALSE;
     }
-    /* align all transfers to 1 sample */
-    ret = snd_pcm_sw_params_set_xfer_align(info->handle, info->swParams, 1);
-    if (ret < 0) {
-        ERROR1("Unable to set transfer align: %s\n", snd_strerror(ret));
-        return FALSE;
-    }
     /* write the parameters to the playback device */
     ret = snd_pcm_sw_params(info->handle, info->swParams);
     if (ret < 0) {
@@ -448,7 +415,6 @@
     int ret = 0;
     AlsaPcmInfo* info = NULL;
     /* snd_pcm_uframes_t is 64 bit on 64-bit systems */
-    snd_pcm_uframes_t alsaPeriodSize = 0;
     snd_pcm_uframes_t alsaBufferSizeInFrames = 0;
 
 
@@ -484,21 +450,13 @@
                                 bufferSizeInBytes / frameSize,
                                 format)) {
                     info->frameSize = frameSize;
-#ifdef ALSA_PCM_NEW_HW_PARAMS_API
-                    ret = snd_pcm_hw_params_get_period_size(info->hwParams, &alsaPeriodSize, &dir);
-                    info->periodSize = (int) alsaPeriodSize;
+                    ret = snd_pcm_hw_params_get_period_size(info->hwParams, &info->periodSize, &dir);
                     if (ret < 0) {
                         ERROR1("ERROR: snd_pcm_hw_params_get_period: %s\n", snd_strerror(ret));
                     }
                     snd_pcm_hw_params_get_periods(info->hwParams, &(info->periods), &dir);
                     snd_pcm_hw_params_get_buffer_size(info->hwParams, &alsaBufferSizeInFrames);
                     info->bufferSizeInBytes = (int) alsaBufferSizeInFrames * frameSize;
-#else
-                    info->periodSize = snd_pcm_hw_params_get_period_size(info->hwParams, &dir);
-                    info->periods = snd_pcm_hw_params_get_periods(info->hwParams, &dir);
-                    info->bufferSizeInBytes = snd_pcm_hw_params_get_buffer_size(info->hwParams) * frameSize;
-                    ret = 0;
-#endif
                     TRACE3("  DAUDIO_Open: period size = %d frames, periods = %d. Buffer size: %d bytes.\n",
                            (int) info->periodSize, info->periods, info->bufferSizeInBytes);
                 }
diff --git a/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_PCMUtils.h b/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_PCMUtils.h
index c8d920f..ca911d2 100644
--- a/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_PCMUtils.h
+++ b/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_PCMUtils.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -24,6 +24,7 @@
  */
 
 // define this with a later version of ALSA than 0.9.0rc3
+// (starting from 1.0.0 it became default behaviour)
 #define ALSA_PCM_NEW_HW_PARAMS_API
 #include <alsa/asoundlib.h>
 #include "Utilities.h"
diff --git a/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_Ports.c b/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_Ports.c
index 465ecad..0db0e6c 100644
--- a/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_Ports.c
+++ b/src/solaris/native/com/sun/media/sound/PLATFORM_API_LinuxOS_ALSA_Ports.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -380,7 +380,7 @@
     void* controls[10];
     int numControls;
     char* portName;
-    int isPlayback;
+    int isPlayback = 0;
     int isMono;
     int isStereo;
     char* type;
diff --git a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c
index 1832401..63addde 100644
--- a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c
+++ b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c
@@ -191,7 +191,7 @@
 
     fp_gdk_threads_enter();
 
-    const char *title = (*env)->GetStringUTFChars(env, jtitle, 0);
+    const char *title = jtitle == NULL? "": (*env)->GetStringUTFChars(env, jtitle, 0);
 
     if (mode == 1) {
         /* Save action */
@@ -212,7 +212,9 @@
         }
     }
 
-    (*env)->ReleaseStringUTFChars(env, jtitle, title);
+    if (jtitle != NULL) {
+      (*env)->ReleaseStringUTFChars(env, jtitle, title);
+    }
 
     /* Set the directory */
     if (jdir != NULL) {
diff --git a/src/solaris/native/sun/xawt/XToolkit.c b/src/solaris/native/sun/xawt/XToolkit.c
index 7202417..4ea6314 100644
--- a/src/solaris/native/sun/xawt/XToolkit.c
+++ b/src/solaris/native/sun/xawt/XToolkit.c
@@ -187,7 +187,9 @@
                          "()Ljava/awt/Point;");
 
     keyclass = (*env)->FindClass(env, "java/awt/event/KeyEvent");
-    DASSERT (keyclass != NULL);
+    if (JNU_IsNull(env, keyclass)) {
+        return;
+    }
 
     componentIDs.isProxyActive =
         (*env)->GetFieldID(env, keyclass, "isProxyActive",
@@ -715,8 +717,10 @@
   if (xawt_root_shell == None){
       if (classXRootWindow == NULL){
           jclass cls_tmp = (*env)->FindClass(env, "sun/awt/X11/XRootWindow");
-          classXRootWindow = (jclass)(*env)->NewGlobalRef(env, cls_tmp);
-          (*env)->DeleteLocalRef(env, cls_tmp);
+          if (!JNU_IsNull(env, cls_tmp)) {
+              classXRootWindow = (jclass)(*env)->NewGlobalRef(env, cls_tmp);
+              (*env)->DeleteLocalRef(env, cls_tmp);
+          }
       }
       if( classXRootWindow != NULL) {
           methodGetXRootWindow = (*env)->GetStaticMethodID(env, classXRootWindow, "getXRootWindow", "()J");
diff --git a/src/windows/classes/java/lang/ProcessEnvironment.java b/src/windows/classes/java/lang/ProcessEnvironment.java
index 77adfc2..c5e4c13 100644
--- a/src/windows/classes/java/lang/ProcessEnvironment.java
+++ b/src/windows/classes/java/lang/ProcessEnvironment.java
@@ -250,8 +250,7 @@
                                    envblock.substring(eql+1,end));
         }
 
-        theCaseInsensitiveEnvironment
-            = new TreeMap<String,String>(nameComparator);
+        theCaseInsensitiveEnvironment = new TreeMap<>(nameComparator);
         theCaseInsensitiveEnvironment.putAll(theEnvironment);
     }
 
@@ -296,8 +295,7 @@
     // Only for use by ProcessImpl.start()
     String toEnvironmentBlock() {
         // Sort Unicode-case-insensitively by name
-        List<Map.Entry<String,String>> list
-            = new ArrayList<Map.Entry<String,String>>(entrySet());
+        List<Map.Entry<String,String>> list = new ArrayList<>(entrySet());
         Collections.sort(list, entryComparator);
 
         StringBuilder sb = new StringBuilder(size()*30);
diff --git a/src/windows/lib/tzmappings b/src/windows/lib/tzmappings
index bbc3ca0..7f6f0d3 100644
--- a/src/windows/lib/tzmappings
+++ b/src/windows/lib/tzmappings
@@ -188,5 +188,6 @@
 UTC-11:921,921::GMT-1100:
 Ulaanbaatar Standard Time:922,922::Asia/Ulaanbaatar:
 Venezuela Standard Time:923,923::America/Caracas:
-Western Brazilian Standard Time:924,924:BR:America/Rio_Branco:
-Armenian Standard Time:925,925:AM:Asia/Yerevan:
+Magadan Standard Time:924,924::Asia/Magadan:
+Western Brazilian Standard Time:925,925:BR:America/Rio_Branco:
+Armenian Standard Time:926,926:AM:Asia/Yerevan:
diff --git a/src/windows/native/java/net/Inet4AddressImpl.c b/src/windows/native/java/net/Inet4AddressImpl.c
index cb132db..197800d 100644
--- a/src/windows/native/java/net/Inet4AddressImpl.c
+++ b/src/windows/native/java/net/Inet4AddressImpl.c
@@ -559,8 +559,8 @@
 
         if (timeout >= 0) {
           optlen = sizeof(connect_rv);
-          if (JVM_GetSockOpt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
-                             &optlen) <0) {
+          if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
+                         &optlen) <0) {
             connect_rv = WSAGetLastError();
           }
 
diff --git a/src/windows/native/java/net/Inet6AddressImpl.c b/src/windows/native/java/net/Inet6AddressImpl.c
index 87f9568..1f9a677 100644
--- a/src/windows/native/java/net/Inet6AddressImpl.c
+++ b/src/windows/native/java/net/Inet6AddressImpl.c
@@ -671,8 +671,8 @@
         if (timeout >= 0) {
           /* has connection been established? */
           optlen = sizeof(connect_rv);
-          if (JVM_GetSockOpt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
-                             &optlen) <0) {
+          if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
+                         &optlen) <0) {
             connect_rv = WSAGetLastError();
           }
 
diff --git a/src/windows/native/sun/windows/Devices.h b/src/windows/native/sun/windows/Devices.h
index e8324ce..748ded2 100644
--- a/src/windows/native/sun/windows/Devices.h
+++ b/src/windows/native/sun/windows/Devices.h
@@ -54,7 +54,7 @@
            InstanceAccess& operator=(const InstanceAccess&);
            InstanceAccess* operator&();
        };
-friend                          InstanceAccess;
+friend class InstanceAccess;
 
 private:
                                 Devices(int numElements);
diff --git a/src/windows/native/sun/windows/awt.h b/src/windows/native/sun/windows/awt.h
index e93dcb1..0ae6511 100644
--- a/src/windows/native/sun/windows/awt.h
+++ b/src/windows/native/sun/windows/awt.h
@@ -173,7 +173,7 @@
 
 // Platform encoding is Unicode (UTF-16), re-define JNU_ functions
 // to proper JNI functions.
-#define JNU_NewStringPlatform(env, x) env->NewString(reinterpret_cast<jchar*>(x), static_cast<jsize>(_tcslen(x)))
+#define JNU_NewStringPlatform(env, x) env->NewString(reinterpret_cast<const jchar*>(x), static_cast<jsize>(_tcslen(x)))
 #define JNU_GetStringPlatformChars(env, x, y) reinterpret_cast<LPCWSTR>(env->GetStringChars(x, y))
 #define JNU_ReleaseStringPlatformChars(env, x, y) env->ReleaseStringChars(x, reinterpret_cast<const jchar*>(y))
 
diff --git a/src/windows/native/sun/windows/awt_Debug.cpp b/src/windows/native/sun/windows/awt_Debug.cpp
index 3d6c424..42e099b 100644
--- a/src/windows/native/sun/windows/awt_Debug.cpp
+++ b/src/windows/native/sun/windows/awt_Debug.cpp
@@ -47,12 +47,21 @@
     return ptr;
 }
 
+void * operator new[](size_t size, const char * filename, int linenumber) {
+    void * ptr = DMem_AllocateBlock(size, filename, linenumber);
+    if (ptr == NULL) {
+        throw std::bad_alloc();
+    }
+
+    return ptr;
+}
+
 #if _MSC_VER >= 1200
 void operator delete(void *ptr, const char*, int) {
     DASSERTMSG(FALSE, "This version of 'delete' should never get called!!!");
 }
 #endif
-void operator delete(void *ptr) {
+void operator delete(void *ptr) throw() {
     DMem_FreeBlock(ptr);
 }
 
diff --git a/src/windows/native/sun/windows/awt_Debug.h b/src/windows/native/sun/windows/awt_Debug.h
index 9fc4ab6..729e652 100644
--- a/src/windows/native/sun/windows/awt_Debug.h
+++ b/src/windows/native/sun/windows/awt_Debug.h
@@ -48,11 +48,14 @@
     };
 
     extern void * operator new(size_t size, const char * filename, int linenumber);
+    extern void * operator new[](size_t size, const char * filename, int linenumber);
+
 #if _MSC_VER >= 1200
     /* VC 6.0 is more strict about enforcing matching placement new & delete */
     extern void operator delete(void *ptr, const char*, int);
 #endif
-    extern void operator delete(void *ptr);
+
+    extern void operator delete(void *ptr) throw();
     extern void DumpClipRectangle(const char * file, int line, int argc, const char * fmt, va_list arglist);
     extern void DumpUpdateRectangle(const char * file, int line, int argc, const char * fmt, va_list arglist);
 
diff --git a/src/windows/native/sun/windows/awt_DesktopProperties.cpp b/src/windows/native/sun/windows/awt_DesktopProperties.cpp
index cf69d13..8d13a97 100644
--- a/src/windows/native/sun/windows/awt_DesktopProperties.cpp
+++ b/src/windows/native/sun/windows/awt_DesktopProperties.cpp
@@ -650,7 +650,7 @@
 }
 
 void AwtDesktopProperties::SetStringProperty(LPCTSTR propName, LPTSTR value) {
-    jstring key = JNU_NewStringPlatform(GetEnv(), const_cast<LPTSTR>(propName));
+    jstring key = JNU_NewStringPlatform(GetEnv(), propName);
     GetEnv()->CallVoidMethod(self,
                              AwtDesktopProperties::setStringPropertyID,
                              key, JNU_NewStringPlatform(GetEnv(), value));
@@ -658,7 +658,7 @@
 }
 
 void AwtDesktopProperties::SetIntegerProperty(LPCTSTR propName, int value) {
-    jstring key = JNU_NewStringPlatform(GetEnv(), const_cast<LPTSTR>(propName));
+    jstring key = JNU_NewStringPlatform(GetEnv(), propName);
     GetEnv()->CallVoidMethod(self,
                              AwtDesktopProperties::setIntegerPropertyID,
                              key, (jint)value);
@@ -666,7 +666,7 @@
 }
 
 void AwtDesktopProperties::SetBooleanProperty(LPCTSTR propName, BOOL value) {
-    jstring key = JNU_NewStringPlatform(GetEnv(), const_cast<LPTSTR>(propName));
+    jstring key = JNU_NewStringPlatform(GetEnv(), propName);
     GetEnv()->CallVoidMethod(self,
                              AwtDesktopProperties::setBooleanPropertyID,
                              key, value ? JNI_TRUE : JNI_FALSE);
@@ -674,7 +674,7 @@
 }
 
 void AwtDesktopProperties::SetColorProperty(LPCTSTR propName, DWORD value) {
-    jstring key = JNU_NewStringPlatform(GetEnv(), const_cast<LPTSTR>(propName));
+    jstring key = JNU_NewStringPlatform(GetEnv(), propName);
     GetEnv()->CallVoidMethod(self,
                              AwtDesktopProperties::setColorPropertyID,
                              key, GetRValue(value), GetGValue(value),
@@ -726,7 +726,7 @@
                         style |= java_awt_Font_ITALIC;
                     }
 
-                    jstring key = JNU_NewStringPlatform(GetEnv(), const_cast<LPTSTR>(propName));
+                    jstring key = JNU_NewStringPlatform(GetEnv(), propName);
                     GetEnv()->CallVoidMethod(self,
                               AwtDesktopProperties::setFontPropertyID,
                               key, fontName, style, pointSize);
@@ -744,7 +744,7 @@
     jint pointSize;
     jint style;
 
-    fontName = JNU_NewStringPlatform(GetEnv(), const_cast<LPWSTR>(font.lfFaceName));
+    fontName = JNU_NewStringPlatform(GetEnv(), font.lfFaceName);
 
 #if 0
     HDC         hdc;
@@ -767,7 +767,7 @@
         style |= java_awt_Font_ITALIC;
     }
 
-    jstring key = JNU_NewStringPlatform(GetEnv(), const_cast<LPTSTR>(propName));
+    jstring key = JNU_NewStringPlatform(GetEnv(), propName);
     GetEnv()->CallVoidMethod(self, AwtDesktopProperties::setFontPropertyID,
                              key, fontName, style, pointSize);
 
@@ -776,8 +776,8 @@
 }
 
 void AwtDesktopProperties::SetSoundProperty(LPCTSTR propName, LPCTSTR winEventName) {
-    jstring key = JNU_NewStringPlatform(GetEnv(), const_cast<LPTSTR>(propName));
-    jstring event = JNU_NewStringPlatform(GetEnv(), const_cast<LPTSTR>(winEventName));
+    jstring key = JNU_NewStringPlatform(GetEnv(), propName);
+    jstring event = JNU_NewStringPlatform(GetEnv(), winEventName);
     GetEnv()->CallVoidMethod(self,
                              AwtDesktopProperties::setSoundPropertyID,
                              key, event);
diff --git a/src/windows/native/sun/windows/awt_Dialog.cpp b/src/windows/native/sun/windows/awt_Dialog.cpp
index 6174750..3de8495 100644
--- a/src/windows/native/sun/windows/awt_Dialog.cpp
+++ b/src/windows/native/sun/windows/awt_Dialog.cpp
@@ -230,7 +230,7 @@
         if (::IsIconic(hWnd)) {
             ::ShowWindow(hWnd, SW_RESTORE);
         }
-        PopupAllDialogs(blocker, TRUE, ::GetForegroundWindow(), FALSE);
+        PopupBlockers(blocker, TRUE, ::GetForegroundWindow(), FALSE);
         // return 1 to prevent the system from allowing the operation
         return 1;
     }
@@ -256,7 +256,7 @@
             HWND blocker = AwtWindow::GetModalBlocker(AwtComponent::GetTopLevelParentForWindow(hWnd));
             if (::IsWindow(blocker)) {
                 BOOL onTaskbar = !(::WindowFromPoint(mhs->pt) == hWnd);
-                PopupAllDialogs(hWnd, FALSE, ::GetForegroundWindow(), onTaskbar);
+                PopupBlockers(blocker, FALSE, ::GetForegroundWindow(), onTaskbar);
                 // return a nonzero value to prevent the system from passing
                 // the message to the target window procedure
                 return 1;
@@ -268,60 +268,60 @@
 }
 
 /*
- * The function goes through the heirarchy of the blocker dialogs and
- * popups all the dialogs. Note that the function starts from the top
- * blocker dialog and goes down to the dialog which is the bottom dialog.
- * Using another traversal may cause to the flickering issue as a bottom
- * dialog will cover a top dialog for some period of time.
+ * The function goes through the hierarchy of the blockers and
+ * popups all the blockers. Note that the function starts from the top
+ * blocker and goes down to the blocker which is the bottom one.
+ * Using another traversal algorithm (bottom->top) may cause to flickering
+ * as the bottom blocker will cover the top blocker for a while.
  */
-void AwtDialog::PopupAllDialogs(HWND dialog, BOOL isModalHook, HWND prevFGWindow, BOOL onTaskbar)
+void AwtDialog::PopupBlockers(HWND blocker, BOOL isModalHook, HWND prevFGWindow, BOOL onTaskbar)
 {
-    HWND blocker = AwtWindow::GetModalBlocker(dialog);
-    BOOL isBlocked = ::IsWindow(blocker);
-    if (isBlocked) {
-        PopupAllDialogs(blocker, isModalHook, prevFGWindow, onTaskbar);
+    HWND nextBlocker = AwtWindow::GetModalBlocker(blocker);
+    BOOL nextBlockerExists = ::IsWindow(nextBlocker);
+    if (nextBlockerExists) {
+        PopupBlockers(nextBlocker, isModalHook, prevFGWindow, onTaskbar);
     }
-    PopupOneDialog(dialog, blocker, isModalHook, prevFGWindow, onTaskbar);
+    PopupBlocker(blocker, nextBlocker, isModalHook, prevFGWindow, onTaskbar);
 }
 
 /*
- * The function popups the dialog, it distinguishes non-blocked dialogs
- * and activates the dialogs (sets as foreground window). If the dialog is
- * blocked, then it changes the Z-order of the dialog.
+ * The function popups the blocker, for a non-blocked blocker we need
+ * to activate the blocker but if a blocker is blocked, then we need
+ * to change z-order of the blocker placing the blocker under the next blocker.
  */
-void AwtDialog::PopupOneDialog(HWND dialog, HWND blocker, BOOL isModalHook, HWND prevFGWindow, BOOL onTaskbar)
+void AwtDialog::PopupBlocker(HWND blocker, HWND nextBlocker, BOOL isModalHook, HWND prevFGWindow, BOOL onTaskbar)
 {
-    if (dialog == AwtToolkit::GetInstance().GetHWnd()) {
+    if (blocker == AwtToolkit::GetInstance().GetHWnd()) {
         return;
     }
 
     // fix for 6494032
-    if (isModalHook && !::IsWindowVisible(dialog)) {
-        ::ShowWindow(dialog, SW_SHOWNA);
+    if (isModalHook && !::IsWindowVisible(blocker)) {
+        ::ShowWindow(blocker, SW_SHOWNA);
     }
 
-    BOOL isBlocked = ::IsWindow(blocker);
+    BOOL nextBlockerExists = ::IsWindow(nextBlocker);
     UINT flags = SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE;
 
-    if (isBlocked) {
+    if (nextBlockerExists) {
         // Fix for 6829546: if blocker is a top-most window, but window isn't, then
         // calling ::SetWindowPos(dialog, blocker, ...) makes window top-most as well
-        BOOL isBlockerTopmost = (::GetWindowLong(blocker, GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
-        BOOL isDialogTopmost = (::GetWindowLong(dialog, GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
-        if (!isBlockerTopmost || isDialogTopmost) {
-            ::SetWindowPos(dialog, blocker, 0, 0, 0, 0, flags);
+        BOOL topmostNextBlocker = (::GetWindowLong(nextBlocker, GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
+        BOOL topmostBlocker = (::GetWindowLong(blocker, GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
+        if (!topmostNextBlocker || topmostBlocker) {
+            ::SetWindowPos(blocker, nextBlocker, 0, 0, 0, 0, flags);
         } else {
-            ::SetWindowPos(dialog, HWND_TOP, 0, 0, 0, 0, flags);
+            ::SetWindowPos(blocker, HWND_TOP, 0, 0, 0, 0, flags);
         }
     } else {
-        ::SetWindowPos(dialog, HWND_TOP, 0, 0, 0, 0, flags);
+        ::SetWindowPos(blocker, HWND_TOP, 0, 0, 0, 0, flags);
         // no beep/flash if the mouse was clicked in the taskbar menu
         // or the dialog is currently inactive
-        if (!isModalHook && !onTaskbar && (dialog == prevFGWindow)) {
-            AnimateModalBlocker(dialog);
+        if (!isModalHook && !onTaskbar && (blocker == prevFGWindow)) {
+            AnimateModalBlocker(blocker);
         }
-        ::BringWindowToTop(dialog);
-        ::SetForegroundWindow(dialog);
+        ::BringWindowToTop(blocker);
+        ::SetForegroundWindow(blocker);
     }
 }
 
diff --git a/src/windows/native/sun/windows/awt_Dialog.h b/src/windows/native/sun/windows/awt_Dialog.h
index 5aa99df..15918a6 100644
--- a/src/windows/native/sun/windows/awt_Dialog.h
+++ b/src/windows/native/sun/windows/awt_Dialog.h
@@ -113,8 +113,8 @@
      */
     static void ModalPerformActivation(HWND hWnd);
 
-    static void PopupAllDialogs(HWND dialog, BOOL isModalHook, HWND prevFGWindow, BOOL onTaskbar);
-    static void PopupOneDialog(HWND dialog, HWND blocker, BOOL isModalHook, HWND prevFGWindow, BOOL onTaskbar);
+    static void PopupBlockers(HWND blocker, BOOL isModalHook, HWND prevFGWindow, BOOL onTaskbar);
+    static void PopupBlocker(HWND blocker, HWND nextBlocker, BOOL isModalHook, HWND prevFGWindow, BOOL onTaskbar);
 
 public:
 
diff --git a/src/windows/native/sun/windows/awt_TextArea.h b/src/windows/native/sun/windows/awt_TextArea.h
index 27b7b00..19a44e7 100644
--- a/src/windows/native/sun/windows/awt_TextArea.h
+++ b/src/windows/native/sun/windows/awt_TextArea.h
@@ -41,9 +41,6 @@
 
 class AwtTextArea : public AwtTextComponent {
 
-    // inner classes
-    class OleCallback;
-
 public:
 
     /* java.awt.TextArea fields ids */
@@ -89,36 +86,11 @@
     static void _ReplaceText(void *param);
 
 protected:
-    INLINE static OleCallback& GetOleCallback() { return sm_oleCallback; }
-    void EditSetSel(CHARRANGE &cr);
-    void EditGetSel(CHARRANGE &cr);
-    LONG EditGetCharFromPos(POINT& pt);
-  private:
-    // RichEdit 1.0 control generates EN_CHANGE notifications not only
-    // on text changes, but also on any character formatting change.
-    // This flag is true when the latter case is detected.
-    BOOL    m_bIgnoreEnChange;
-
-    // RichEdit 1.0 control undoes a character formatting change
-    // if it is the latest. We don't create our own undo buffer,
-    // but just prohibit undo in case if the latest operation
-    // is a formatting change.
-    BOOL    m_bCanUndo;
-
-    HWND    m_hEditCtrl;
-    static WNDPROC sm_pDefWindowProc;
-
-    LONG    m_lHDeltaAccum;
-    LONG    m_lVDeltaAccum;
-
-
-    static OleCallback sm_oleCallback;
 
     /*****************************************************************
      * Inner class OleCallback declaration.
      */
-
-    class AwtTextArea::OleCallback : public IRichEditOleCallback {
+    class OleCallback : public IRichEditOleCallback {
     public:
         OleCallback();
 
@@ -143,7 +115,32 @@
                                     CHARRANGE FAR * pchrg, HMENU FAR * phmenu);
     private:
         ULONG             m_refs; // Reference count
-    };
+    };//OleCallback class
+
+    INLINE static OleCallback& GetOleCallback() { return sm_oleCallback; }
+    void EditSetSel(CHARRANGE &cr);
+    void EditGetSel(CHARRANGE &cr);
+    LONG EditGetCharFromPos(POINT& pt);
+  private:
+    // RichEdit 1.0 control generates EN_CHANGE notifications not only
+    // on text changes, but also on any character formatting change.
+    // This flag is true when the latter case is detected.
+    BOOL    m_bIgnoreEnChange;
+
+    // RichEdit 1.0 control undoes a character formatting change
+    // if it is the latest. We don't create our own undo buffer,
+    // but just prohibit undo in case if the latest operation
+    // is a formatting change.
+    BOOL    m_bCanUndo;
+
+    HWND    m_hEditCtrl;
+    static WNDPROC sm_pDefWindowProc;
+
+    LONG    m_lHDeltaAccum;
+    LONG    m_lVDeltaAccum;
+
+
+    static OleCallback sm_oleCallback;
 
 };
 
diff --git a/src/windows/native/sun/windows/awt_Toolkit.h b/src/windows/native/sun/windows/awt_Toolkit.h
index f1bfd11..3ebd465 100644
--- a/src/windows/native/sun/windows/awt_Toolkit.h
+++ b/src/windows/native/sun/windows/awt_Toolkit.h
@@ -110,7 +110,7 @@
       private:
         const CriticalSection& critSec;
     };
-    friend Lock;
+    friend class Lock;
 
   private:
     CRITICAL_SECTION rep;
diff --git a/test/com/sun/awt/Translucency/WindowOpacity.java b/test/com/sun/awt/Translucency/WindowOpacity.java
index bf4e74d..a5d8026 100644
--- a/test/com/sun/awt/Translucency/WindowOpacity.java
+++ b/test/com/sun/awt/Translucency/WindowOpacity.java
@@ -64,6 +64,7 @@
         boolean passed;
 
         Frame f = new Frame("Opacity test");
+        f.setUndecorated(true);
 
         passed = false;
         try {
diff --git a/test/java/awt/Insets/WindowWithWarningTest/WindowWithWarningTest.html b/test/java/awt/Insets/WindowWithWarningTest/WindowWithWarningTest.html
deleted file mode 100644
index ad6fa60..0000000
--- a/test/java/awt/Insets/WindowWithWarningTest/WindowWithWarningTest.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<html>
-<!--
-        @test
-        @bug 6391770
-        @summary Content of the Window should be laid out in the area left after WarningWindow was added.
-        @author Yuri Nesterenko
-        @run applet WindowWithWarningTest.html
--->
-
-  <head>
-    <title>WindowWithWarningTest</title>
-  </head>
-  <pre>
-  This test will run automatically.
-  </pre>
-  <body>
-    <applet code="WindowWithWarningTest.class" width=350 height=300></applet>
-  </body>
-</html>
-
diff --git a/test/java/awt/Insets/WindowWithWarningTest/WindowWithWarningTest.java b/test/java/awt/Insets/WindowWithWarningTest/WindowWithWarningTest.java
deleted file mode 100644
index ab9ea69..0000000
--- a/test/java/awt/Insets/WindowWithWarningTest/WindowWithWarningTest.java
+++ /dev/null
@@ -1,315 +0,0 @@
-/*
- * Copyright (c) 2006, 2008, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-
-/*
-  test
-  @bug 6391770
-  @summary Content of the Window should be laid out in the area left after WarningWindow was added.
-  @author yuri nesterenko: area=
-  @run applet WindowWithWarningTest.html
-*/
-
-// Note there is no @ in front of test above.  This is so that the
-//  harness will not mistake this file as a test file.  It should
-//  only see the html file as a test file. (the harness runs all
-//  valid test files, so it would run this test twice if this file
-//  were valid as well as the html file.)
-// Also, note the area= after Your Name in the author tag.  Here, you
-//  should put which functional area the test falls in.  See the
-//  AWT-core home page -> test areas and/or -> AWT team  for a list of
-//  areas.
-// Note also the 'AutomaticAppletTest.html' in the run tag.  This should
-//  be changed to the name of the test.
-
-
-/**
- * WindowWithWarningTest.java
- *
- * summary:
- */
-
-import java.applet.Applet;
-import java.awt.*;
-import java.awt.event.*;
-import javax.swing.*;
-
-//Automated tests should run as applet tests if possible because they
-// get their environments cleaned up, including AWT threads, any
-// test created threads, and any system resources used by the test
-// such as file descriptors.  (This is normally not a problem as
-// main tests usually run in a separate VM, however on some platforms
-// such as the Mac, separate VMs are not possible and non-applet
-// tests will cause problems).  Also, you don't have to worry about
-// synchronisation stuff in Applet tests they way you do in main
-// tests...
-
-
-public class WindowWithWarningTest extends Applet
-{
-    //Declare things used in the test, like buttons and labels here
-    boolean buttonClicked = false;
-    public static final int MAX_COUNT = 100;
-
-    public void init()
-    {
-        //Create instructions for the user here, as well as set up
-        // the environment -- set the layout manager, add buttons,
-        // etc.
-
-        this.setLayout (new BorderLayout ());
-
-        String[] instructions =
-        {
-            "This is an AUTOMATIC test",
-            "simply wait until it is done"
-        };
-        //Sysout.createDialog( );
-        //Sysout.printInstructions( instructions );
-
-    }//End  init()
-    public void start ()
-    {
-        //Get things going.  Request focus, set size, et cetera
-        System.setSecurityManager( new SecurityManager() {
-        // deny AWTPermission("showWindowWithoutWarningBanner")
-            public boolean checkTopLevelWindow(Object window) {
-                return false;
-            }
-         });
-        JFrame frame = new JFrame("Window Test");
-        frame.setBounds(50, 50, 200, 200);
-        frame.show();
-
-        JWindow window = new JWindow( frame );
-        JButton jbutton1 = new JButton( "First" );
-        jbutton1.addMouseListener( new MouseAdapter() {
-            public void mousePressed( MouseEvent me ) {
-                buttonClicked = true;
-            }
-         });
-        JButton jbutton2 = new JButton( "Second" );
-        window.setLocation( 300, 300 );
-
-        window.add("North", jbutton1);
-        window.add("South", jbutton2);
-
-        window.pack();
-        window.show();
-        //wait for frame to show:
-        getLocation( frame );
-        window.toFront();
-
-        Dimension size0 = window.getSize();
-        Dimension size1 = null;
-        try {
-            Robot robot = new Robot();
-
-            robot.delay(500);
-            window.pack();
-            robot.delay(500);
-            window.pack();
-            // size1 must be the same as size0
-            size1 = window.getSize();
-            robot.delay(500);
-            Point pt = jbutton1.getLocationOnScreen();
-            robot.mouseMove((int) jbutton1.getLocationOnScreen().x + jbutton1.getWidth() / 2,
-                            (int) jbutton1.getLocationOnScreen().y + jbutton1.getHeight() / 2);
-            robot.delay(500);
-            robot.mousePress(MouseEvent.BUTTON1_MASK);
-            robot.delay(100);
-            robot.mouseRelease(MouseEvent.BUTTON1_MASK);
-            robot.delay(2000);
-         }catch(Exception e) {
-            throw new RuntimeException( "Exception "+e );
-         }
-         if( !size0.equals(size1) ) {
-            throw new RuntimeException( "Wrong Window size after multiple pack()s");
-         }
-         if( !buttonClicked ) {
-            throw new RuntimeException( "Button was not clicked");
-         }
-         window.dispose();
-         frame.dispose();
-
-         System.out.println("Test Passed.");
-    }// start()
-    public static Point getLocation( Component co ) throws RuntimeException {
-       Point pt = null;
-       boolean bFound = false;
-       int count = 0;
-       while( !bFound ) {
-          try {
-             pt = co.getLocationOnScreen();
-             bFound = true;
-          }catch( Exception ex ) {
-             bFound = false;
-             count++;
-          }
-          if( !bFound && count > MAX_COUNT ) {
-             throw new RuntimeException("don't see a component to get location");
-          }
-       }
-       return pt;
-    }
-
-
-}// class AutomaticAppletTest
-
-
-/****************************************************
- Standard Test Machinery
- DO NOT modify anything below -- it's a standard
-  chunk of code whose purpose is to make user
-  interaction uniform, and thereby make it simpler
-  to read and understand someone else's test.
- ****************************************************/
-
-/**
- This is part of the standard test machinery.
- It creates a dialog (with the instructions), and is the interface
-  for sending text messages to the user.
- To print the instructions, send an array of strings to Sysout.createDialog
-  WithInstructions method.  Put one line of instructions per array entry.
- To display a message for the tester to see, simply call Sysout.println
-  with the string to be displayed.
- This mimics System.out.println but works within the test harness as well
-  as standalone.
- */
-
-class Sysout
-{
-    private static TestDialog dialog;
-
-    public static void createDialogWithInstructions( String[] instructions )
-    {
-        dialog = new TestDialog( new Frame(), "Instructions" );
-        dialog.printInstructions( instructions );
-        dialog.setVisible(true);
-        println( "Any messages for the tester will display here." );
-    }
-
-    public static void createDialog( )
-    {
-        dialog = new TestDialog( new Frame(), "Instructions" );
-        String[] defInstr = { "Instructions will appear here. ", "" } ;
-        dialog.printInstructions( defInstr );
-        dialog.setVisible(true);
-        println( "Any messages for the tester will display here." );
-    }
-
-
-    public static void printInstructions( String[] instructions )
-    {
-        dialog.printInstructions( instructions );
-    }
-
-
-    public static void println( String messageIn )
-    {
-        dialog.displayMessage( messageIn );
-    }
-
-}// Sysout  class
-
-/**
-  This is part of the standard test machinery.  It provides a place for the
-   test instructions to be displayed, and a place for interactive messages
-   to the user to be displayed.
-  To have the test instructions displayed, see Sysout.
-  To have a message to the user be displayed, see Sysout.
-  Do not call anything in this dialog directly.
-  */
-class TestDialog extends Dialog
-{
-
-    TextArea instructionsText;
-    TextArea messageText;
-    int maxStringLength = 80;
-
-    //DO NOT call this directly, go through Sysout
-    public TestDialog( Frame frame, String name )
-    {
-        super( frame, name );
-        int scrollBoth = TextArea.SCROLLBARS_BOTH;
-        instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
-        add( "North", instructionsText );
-
-        messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
-        add("Center", messageText);
-
-        pack();
-
-        show();
-    }// TestDialog()
-
-    //DO NOT call this directly, go through Sysout
-    public void printInstructions( String[] instructions )
-    {
-        //Clear out any current instructions
-        instructionsText.setText( "" );
-
-        //Go down array of instruction strings
-
-        String printStr, remainingStr;
-        for( int i=0; i < instructions.length; i++ )
-        {
-            //chop up each into pieces maxSringLength long
-            remainingStr = instructions[ i ];
-            while( remainingStr.length() > 0 )
-            {
-                //if longer than max then chop off first max chars to print
-                if( remainingStr.length() >= maxStringLength )
-                {
-                    //Try to chop on a word boundary
-                    int posOfSpace = remainingStr.
-                        lastIndexOf( ' ', maxStringLength - 1 );
-
-                    if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
-
-                    printStr = remainingStr.substring( 0, posOfSpace + 1 );
-                    remainingStr = remainingStr.substring( posOfSpace + 1 );
-                }
-                //else just print
-                else
-                {
-                    printStr = remainingStr;
-                    remainingStr = "";
-                }
-
-                instructionsText.append( printStr + "\n" );
-
-            }// while
-
-        }// for
-
-    }//printInstructions()
-
-    //DO NOT call this directly, go through Sysout
-    public void displayMessage( String messageIn )
-    {
-        messageText.append( messageIn + "\n" );
-        System.out.println(messageIn);
-    }
-
-}// TestDialog  class
diff --git a/test/java/awt/xembed/server/TestXEmbedServer.java b/test/java/awt/xembed/server/TestXEmbedServer.java
index d1ef46d..5675652 100644
--- a/test/java/awt/xembed/server/TestXEmbedServer.java
+++ b/test/java/awt/xembed/server/TestXEmbedServer.java
@@ -31,6 +31,9 @@
 import java.awt.datatransfer.*;
 
 public abstract class TestXEmbedServer {
+    // vertical position of server AND client windows
+    private static final int VERTICAL_POSITION = 200;
+
     private static final Logger log = Logger.getLogger("test.xembed");
     Frame f;
     Canvas client;
@@ -161,10 +164,10 @@
         dummy = new JFrame("Dummy");
         dummy.getContentPane().add(new JButton("Button"));
         dummy.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
-        dummy.setBounds(0, 0, 100, 100);
+        dummy.setBounds(0, VERTICAL_POSITION, 100, 100);
         dummy.setVisible(true);
 
-        f.setBounds(300, 0, 800, 300);
+        f.setBounds(300, VERTICAL_POSITION, 800, 300);
         f.setVisible(true);
     }
 
diff --git a/test/java/io/Serializable/NPEProvoker/NPEProvoker.java b/test/java/io/Serializable/NPEProvoker/NPEProvoker.java
index 6edae09..47a8516 100644
--- a/test/java/io/Serializable/NPEProvoker/NPEProvoker.java
+++ b/test/java/io/Serializable/NPEProvoker/NPEProvoker.java
@@ -56,7 +56,7 @@
     public static void main(String[] args) {
         System.err.println("\n Regression test for bug 6541870\n");
         try {
-            ArrayList<NPEProvoker> list = new ArrayList<NPEProvoker>();
+            ArrayList<NPEProvoker> list = new ArrayList<>();
             list.add(new NPEProvoker());
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(baos);
diff --git a/test/java/lang/instrument/ilib/Inject.java b/test/java/lang/instrument/ilib/Inject.java
index af93956..03a85a6 100644
--- a/test/java/lang/instrument/ilib/Inject.java
+++ b/test/java/lang/instrument/ilib/Inject.java
@@ -107,7 +107,7 @@
     class IndexedInjector implements TrackerInjector {
         int counter = 0;
         int tracker;
-        List<Info> infoList = new ArrayList<Info>();
+        List<Info> infoList = new ArrayList<>();
 
         public int stackSize(int currentSize) {
             return currentSize + 1;
diff --git a/test/java/lang/instrument/ilib/InjectBytecodes.java b/test/java/lang/instrument/ilib/InjectBytecodes.java
index d1dbd8a..35e1858 100644
--- a/test/java/lang/instrument/ilib/InjectBytecodes.java
+++ b/test/java/lang/instrument/ilib/InjectBytecodes.java
@@ -50,7 +50,7 @@
     private final Injector[] after  = new Injector[256];
     private final String className;
     private final String methodName;
-    private final Map<Integer,byte[]> snippets = new HashMap<Integer,byte[]>();
+    private final Map<Integer,byte[]> snippets = new HashMap<>();
 
     private int pos;
     private int newPos;
diff --git a/test/java/lang/reflect/Generics/TestPlainArrayNotGeneric.java b/test/java/lang/reflect/Generics/TestPlainArrayNotGeneric.java
index 27f5404..de25d58 100644
--- a/test/java/lang/reflect/Generics/TestPlainArrayNotGeneric.java
+++ b/test/java/lang/reflect/Generics/TestPlainArrayNotGeneric.java
@@ -103,7 +103,7 @@
         }
     }
 
-    private static final Set<Type> checking = new HashSet<Type>();
+    private static final Set<Type> checking = new HashSet<>();
 
     private static void check(Type t, String what) {
         if (t == null || !checking.add(t))
diff --git a/test/java/text/Format/DateFormat/ISO8601ZoneTest.java b/test/java/text/Format/DateFormat/ISO8601ZoneTest.java
index 2179948..2a5c241 100644
--- a/test/java/text/Format/DateFormat/ISO8601ZoneTest.java
+++ b/test/java/text/Format/DateFormat/ISO8601ZoneTest.java
@@ -60,48 +60,51 @@
         "yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
     };
 
+    // badData[][0] - format
+    // badData[][1] - (bad) text to be parsed
+    // badData[][2] - subtext at the end of which a parse error is detected
     static final String[][] badData = {
-        { "X", "1" },
-        { "X", "+1" },
-        { "X", "-2" },
-        { "X", "-24" },
-        { "X", "+24" },
+        { "X", "1", "1" },
+        { "X", "+1", "+1" },
+        { "X", "-2", "-2" },
+        { "X", "-24", "-2" },
+        { "X", "+24", "+2" },
 
-        { "XX", "9" },
-        { "XX", "23" },
-        { "XX", "234" },
-        { "XX", "3456" },
-        { "XX", "23456" },
-        { "XX", "+1" },
-        { "XX", "-12" },
-        { "XX", "+123" },
-        { "XX", "-12:34" },
-        { "XX", "+12:34" },
-        { "XX", "-2423" },
-        { "XX", "+2423" },
-        { "XX", "-1260" },
-        { "XX", "+1260" },
+        { "XX", "9", "9" },
+        { "XX", "23", "2" },
+        { "XX", "234", "2" },
+        { "XX", "3456", "3" },
+        { "XX", "23456", "2" },
+        { "XX", "+1", "+1" },
+        { "XX", "-12", "-12" },
+        { "XX", "+123", "+123" },
+        { "XX", "-12:34", "-12" },
+        { "XX", "+12:34", "+12" },
+        { "XX", "-2423", "-2" },
+        { "XX", "+2423", "+2" },
+        { "XX", "-1260", "-126" },
+        { "XX", "+1260", "+126" },
 
-        { "XXX", "9" },
-        { "XXX", "23" },
-        { "XXX", "234" },
-        { "XXX", "3456" },
-        { "XXX", "23456" },
-        { "XXX", "2:34" },
-        { "XXX", "12:4" },
-        { "XXX", "12:34" },
-        { "XXX", "-1" },
-        { "XXX", "+1" },
-        { "XXX", "-12" },
-        { "XXX", "+12" },
-        { "XXX", "-123" },
-        { "XXX", "+123" },
-        { "XXX", "-1234" },
-        { "XXX", "+1234" },
-        { "XXX", "+24:23" },
-        { "XXX", "+12:60" },
-        { "XXX", "+1:23" },
-        { "XXX", "+12:3" },
+        { "XXX", "9", "9" },
+        { "XXX", "23", "2" },
+        { "XXX", "234", "2" },
+        { "XXX", "3456", "3" },
+        { "XXX", "23456", "2" },
+        { "XXX", "2:34", "2" },
+        { "XXX", "12:4", "1" },
+        { "XXX", "12:34", "1" },
+        { "XXX", "-1", "-1" },
+        { "XXX", "+1", "+1" },
+        { "XXX", "-12", "-12" },
+        { "XXX", "+12", "+12" },
+        { "XXX", "-123", "-12" },
+        { "XXX", "+123", "+12" },
+        { "XXX", "-1234", "-12" },
+        { "XXX", "+1234", "+12" },
+        { "XXX", "+24:23", "+2" },
+        { "XXX", "+12:60", "+12:6" },
+        { "XXX", "+1:23", "+1" },
+        { "XXX", "+12:3", "+12:3" },
     };
 
     static String[] badFormats = {
@@ -110,6 +113,8 @@
 
     public static void main(String[] args) throws Exception {
         TimeZone tz = TimeZone.getDefault();
+        Locale loc = Locale.getDefault();
+        Locale.setDefault(Locale.US);
 
         try {
             for (int i = 0; i < formatData.length; i++) {
@@ -128,7 +133,7 @@
             }
 
             for (String[] d : badData) {
-                badDataParsing(d[0], d[1]);
+                badDataParsing(d[0], d[1], d[2].length());
             }
 
             for (String fmt : badFormats) {
@@ -136,6 +141,7 @@
             }
         } finally {
             TimeZone.setDefault(tz);
+            Locale.setDefault(loc);
         }
 
     }
@@ -188,15 +194,24 @@
     }
 
 
-    static void badDataParsing(String fmt, String text) {
+    static void badDataParsing(String fmt, String text, int expectedErrorIndex) {
+        SimpleDateFormat sdf = new SimpleDateFormat(fmt);
         try {
-            SimpleDateFormat sdf = new SimpleDateFormat(fmt);
             sdf.parse(text);
             throw new RuntimeException("didn't throw an exception: fmt=" + fmt
                                        + ", text=" + text);
         } catch (ParseException e) {
             // OK
         }
+
+        ParsePosition pos = new ParsePosition(0);
+        Date d = sdf.parse(text, pos);
+        int errorIndex = pos.getErrorIndex();
+        if (d != null || errorIndex != expectedErrorIndex) {
+            throw new RuntimeException("Bad error index=" + errorIndex
+                                       + ", expected=" + expectedErrorIndex
+                                       + ", fmt=" + fmt + ", text=" + text);
+        }
     }
 
     static void badFormat(String fmt) {
diff --git a/test/java/text/Format/MessageFormat/Bug7003643.java b/test/java/text/Format/MessageFormat/Bug7003643.java
new file mode 100644
index 0000000..aeb722c
--- /dev/null
+++ b/test/java/text/Format/MessageFormat/Bug7003643.java
@@ -0,0 +1,73 @@
+/*
+ * 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.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 7003643
+ * @summary Make sure MessageFormat.toPattern produces correct quoting. (SPI part is tested in PluggableLocale tests.)
+ */
+
+import java.text.*;
+import java.util.*;
+
+public class Bug7003643 {
+    private static final int N = 5;
+
+    private static final String[] elements = {
+        "'{'", "'{", "{", "''", "}", "a", "'",
+    };
+
+    public static void main(String[] args) {
+        Random rand = new Random();
+        int count = 0;
+        int max = (int) (Math.pow((double)elements.length, (double)N)/0.52);
+        while (count < max) {
+            // Create a random pattern. If the produced pattern is
+            // valid, then proceed with the round-trip testing.
+            StringBuilder sb = new StringBuilder();
+            for (int i = 0; i < N; i++) {
+                sb.append(elements[rand.nextInt(elements.length)]);
+            }
+            String pattern = sb.toString();
+            MessageFormat mf = null;
+            try {
+                mf = new MessageFormat(pattern);
+            } catch (IllegalArgumentException e) {
+                // bad pattern data
+            }
+            if (mf == null) {
+                continue;
+            }
+            count++;
+            String res1 = MessageFormat.format(pattern, 123);
+            String toPattern = mf.toPattern();
+            String res2 = MessageFormat.format(toPattern, 123);
+            if (!res1.equals(res2)) {
+                String s = String.format("Failed%n      pattern=\"%s\"  =>  result=\"%s\"%n"
+                                         + "  toPattern()=\"%s\"  =>  result=\"%s\"%n",
+                                         pattern, res1, toPattern, res2);
+                throw new RuntimeException(s);
+            }
+        }
+    }
+}
diff --git a/test/java/util/Locale/LocaleTest.java b/test/java/util/Locale/LocaleTest.java
index af00c6b..0c21a8e 100644
--- a/test/java/util/Locale/LocaleTest.java
+++ b/test/java/util/Locale/LocaleTest.java
@@ -24,7 +24,8 @@
  * @test
  * @bug 4052404 4052440 4084688 4092475 4101316 4105828 4107014 4107953 4110613
  * 4118587 4118595 4122371 4126371 4126880 4135316 4135752 4139504 4139940 4143951
- * 4147315 4147317 4147552 4335196 4778440 5010672 6475525 6544471 6627549 6786276
+ * 4147315 4147317 4147552 4335196 4778440 4940539 5010672 6475525 6544471 6627549
+ * 6786276
  * @summary test Locales
  */
 /*
@@ -895,17 +896,28 @@
     }
 
     /**
-     * @bug 4147317
-     * java.util.Locale.getISO3Language() works wrong for non ISO-3166 codes.
-     * Should throw an exception for unknown locales
+     * @bug 4147317 4940539
+     * java.util.Locale.getISO3Language() works wrong for non ISO-639 codes.
+     * Should throw an exception for unknown locales, except they have three
+     * letter language codes.
      */
     public void Test4147317() {
-        // Try with codes that are the wrong length but happen to match text
-        // at a valid offset in the mapping table
+        // Try a three letter language code, and check whether it is
+        // returned as is.
         Locale locale = new Locale("aaa", "CCC");
 
+        String result = locale.getISO3Language();
+        if (!result.equals("aaa")) {
+            errln("ERROR: getISO3Language() returns: " + result +
+                " for locale '" + locale + "' rather than returning it as is" );
+        }
+
+        // Try an invalid two letter language code, and check whether it
+        // throws a MissingResourceException.
+        locale = new Locale("zz", "CCC");
+
         try {
-            String result = locale.getISO3Language();
+            result = locale.getISO3Language();
 
             errln("ERROR: getISO3Language() returns: " + result +
                 " for locale '" + locale + "' rather than exception" );
diff --git a/test/java/util/PluggableLocale/DateFormatProviderTest.java b/test/java/util/PluggableLocale/DateFormatProviderTest.java
index 6112b68..6d5ecd2 100644
--- a/test/java/util/PluggableLocale/DateFormatProviderTest.java
+++ b/test/java/util/PluggableLocale/DateFormatProviderTest.java
@@ -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
@@ -44,6 +44,7 @@
         availableLocalesTest();
         objectValidityTest();
         extendedVariantTest();
+        messageFormatTest();
     }
 
     void availableLocalesTest() {
@@ -118,4 +119,48 @@
             }
         }
     }
+
+
+    private static final String[] TYPES = {
+        "date",
+        "time"
+    };
+    private static final String[] MODIFIERS = {
+        "",
+        "short",
+        "medium", // Same as DEFAULT
+        "long",
+        "full"
+    };
+
+    void messageFormatTest() {
+        for (Locale target : providerloc) {
+            for (String type : TYPES) {
+                for (String modifier : MODIFIERS) {
+                    String pattern, expected;
+                    if (modifier.equals("")) {
+                        pattern = String.format("%s={0,%s}", type, type);
+                    } else {
+                        pattern = String.format("%s={0,%s,%s}", type, type, modifier);
+                    }
+                    if (modifier.equals("medium")) {
+                        // medium is default.
+                        expected = String.format("%s={0,%s}", type, type);
+                    } else {
+                        expected = pattern;
+                    }
+                    MessageFormat mf = new MessageFormat(pattern, target);
+                    Format[] fmts = mf.getFormats();
+                    if (fmts[0] instanceof SimpleDateFormat) {
+                        continue;
+                    }
+                    String toPattern = mf.toPattern();
+                    if (!toPattern.equals(expected)) {
+                        throw new RuntimeException("messageFormatTest: got '" + toPattern
+                                                   + "', expected '" + expected + "'");
+                    }
+                }
+            }
+        }
+    }
 }
diff --git a/test/java/util/PluggableLocale/DateFormatProviderTest.sh b/test/java/util/PluggableLocale/DateFormatProviderTest.sh
index 0d7ad95..228a248 100644
--- a/test/java/util/PluggableLocale/DateFormatProviderTest.sh
+++ b/test/java/util/PluggableLocale/DateFormatProviderTest.sh
@@ -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
@@ -23,6 +23,6 @@
 #!/bin/sh
 #
 # @test
-# @bug 4052440
+# @bug 4052440 7003643
 # @summary DateFormatProvider tests
 # @run shell ExecTest.sh foo DateFormatProviderTest true
diff --git a/test/java/util/PluggableLocale/NumberFormatProviderTest.java b/test/java/util/PluggableLocale/NumberFormatProviderTest.java
index 93540bf..a7ebfb7 100644
--- a/test/java/util/PluggableLocale/NumberFormatProviderTest.java
+++ b/test/java/util/PluggableLocale/NumberFormatProviderTest.java
@@ -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
@@ -29,6 +29,8 @@
 import sun.util.*;
 import sun.util.resources.*;
 
+import com.foo.FooNumberFormat;
+
 public class NumberFormatProviderTest extends ProviderTest {
 
     com.foo.NumberFormatProviderImpl nfp = new com.foo.NumberFormatProviderImpl();
@@ -43,6 +45,7 @@
     NumberFormatProviderTest() {
         availableLocalesTest();
         objectValidityTest();
+        messageFormatTest();
     }
 
     void availableLocalesTest() {
@@ -72,14 +75,10 @@
             }
 
             // result object
-            String resultCur =
-                ((DecimalFormat)NumberFormat.getCurrencyInstance(target)).toPattern();
-            String resultInt =
-                ((DecimalFormat)NumberFormat.getIntegerInstance(target)).toPattern();
-            String resultNum =
-                ((DecimalFormat)NumberFormat.getNumberInstance(target)).toPattern();
-            String resultPer =
-                ((DecimalFormat)NumberFormat.getPercentInstance(target)).toPattern();
+            String resultCur = getPattern(NumberFormat.getCurrencyInstance(target));
+            String resultInt = getPattern(NumberFormat.getIntegerInstance(target));
+            String resultNum = getPattern(NumberFormat.getNumberInstance(target));
+            String resultPer = getPattern(NumberFormat.getPercentInstance(target));
 
             // provider's object (if any)
             String providersCur = null;
@@ -87,21 +86,21 @@
             String providersNum = null;
             String providersPer = null;
             if (providerloc.contains(target)) {
-                DecimalFormat dfCur = (DecimalFormat)nfp.getCurrencyInstance(target);
+                NumberFormat dfCur = nfp.getCurrencyInstance(target);
                 if (dfCur != null) {
-                    providersCur = dfCur.toPattern();
+                    providersCur = getPattern(dfCur);
                 }
-                DecimalFormat dfInt = (DecimalFormat)nfp.getIntegerInstance(target);
+                NumberFormat dfInt = nfp.getIntegerInstance(target);
                 if (dfInt != null) {
-                    providersInt = dfInt.toPattern();
+                    providersInt = getPattern(dfInt);
                 }
-                DecimalFormat dfNum = (DecimalFormat)nfp.getNumberInstance(target);
+                NumberFormat dfNum = nfp.getNumberInstance(target);
                 if (dfNum != null) {
-                    providersNum = dfNum.toPattern();
+                    providersNum = getPattern(dfNum);
                 }
-                DecimalFormat dfPer = (DecimalFormat)nfp.getPercentInstance(target);
+                NumberFormat dfPer = nfp.getPercentInstance(target);
                 if (dfPer != null) {
-                    providersPer = dfPer.toPattern();
+                    providersPer = getPattern(dfPer);
                 }
             }
 
@@ -174,4 +173,35 @@
             }
         }
     }
+
+    private static String getPattern(NumberFormat nf) {
+        if (nf instanceof DecimalFormat) {
+            return ((DecimalFormat)nf).toPattern();
+        }
+        if (nf instanceof FooNumberFormat) {
+            return ((FooNumberFormat)nf).toPattern();
+        }
+        return null;
+    }
+
+    private static final String[] NUMBER_PATTERNS = {
+        "num={0,number}",
+        "num={0,number,currency}",
+        "num={0,number,percent}",
+        "num={0,number,integer}"
+    };
+
+    void messageFormatTest() {
+        for (Locale target : providerloc) {
+            for (String pattern : NUMBER_PATTERNS) {
+                MessageFormat mf = new MessageFormat(pattern, target);
+                String toPattern = mf.toPattern();
+                if (!pattern.equals(toPattern)) {
+                    throw new RuntimeException("MessageFormat.toPattern: got '"
+                                               + toPattern
+                                               + "', expected '" + pattern + "'");
+                }
+            }
+        }
+    }
 }
diff --git a/test/java/util/PluggableLocale/NumberFormatProviderTest.sh b/test/java/util/PluggableLocale/NumberFormatProviderTest.sh
index 7967da9..7f4e902 100644
--- a/test/java/util/PluggableLocale/NumberFormatProviderTest.sh
+++ b/test/java/util/PluggableLocale/NumberFormatProviderTest.sh
@@ -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
@@ -23,6 +23,6 @@
 #!/bin/sh
 #
 # @test
-# @bug 4052440
+# @bug 4052440 7003643
 # @summary NumberFormatProvider tests
 # @run shell ExecTest.sh foo NumberFormatProviderTest true
diff --git a/test/java/util/PluggableLocale/fooprovider.jar b/test/java/util/PluggableLocale/fooprovider.jar
index 29ea53f..c1b5723 100644
--- a/test/java/util/PluggableLocale/fooprovider.jar
+++ b/test/java/util/PluggableLocale/fooprovider.jar
Binary files differ
diff --git a/test/java/util/PluggableLocale/providersrc/DateFormatProviderImpl.java b/test/java/util/PluggableLocale/providersrc/DateFormatProviderImpl.java
index 25e7b17..55bc8d5 100644
--- a/test/java/util/PluggableLocale/providersrc/DateFormatProviderImpl.java
+++ b/test/java/util/PluggableLocale/providersrc/DateFormatProviderImpl.java
@@ -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
@@ -42,7 +42,7 @@
 
     static String[] datePattern = {
         "yyyy'\u5e74'M'\u6708'd'\u65e5'", // full date pattern
-        "yyyy/MM/dd", // long date pattern
+        "yyyy/MMM/dd", // long date pattern
         "yyyy/MM/dd", // medium date pattern
         "yy/MM/dd" // short date pattern
     };
@@ -68,7 +68,7 @@
     public DateFormat getDateInstance(int style, Locale locale) {
         for (int i = 0; i < avail.length; i ++) {
             if (Utils.supportsLocale(avail[i], locale)) {
-                return new SimpleDateFormat(datePattern[style]+dialect[i], locale);
+                return new FooDateFormat(datePattern[style]+dialect[i], locale);
             }
         }
         throw new IllegalArgumentException("locale is not supported: "+locale);
@@ -77,7 +77,7 @@
     public DateFormat getTimeInstance(int style, Locale locale) {
         for (int i = 0; i < avail.length; i ++) {
             if (Utils.supportsLocale(avail[i], locale)) {
-                return new SimpleDateFormat(timePattern[style]+dialect[i], locale);
+                return new FooDateFormat(timePattern[style]+dialect[i], locale);
             }
         }
         throw new IllegalArgumentException("locale is not supported: "+locale);
@@ -86,7 +86,7 @@
     public DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale locale) {
         for (int i = 0; i < avail.length; i ++) {
             if (Utils.supportsLocale(avail[i], locale)) {
-                return new SimpleDateFormat(
+                return new FooDateFormat(
                     datePattern[dateStyle]+" "+timePattern[timeStyle]+dialect[i], locale);
             }
         }
diff --git a/test/java/util/PluggableLocale/providersrc/FooDateFormat.java b/test/java/util/PluggableLocale/providersrc/FooDateFormat.java
new file mode 100644
index 0000000..80d4ce2
--- /dev/null
+++ b/test/java/util/PluggableLocale/providersrc/FooDateFormat.java
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ *
+ * 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.foo;
+
+import java.text.*;
+import java.util.*;
+
+/**
+ * FooDateFormat provides SimpleDateFormat methods required for the SPI testing.
+ */
+public class FooDateFormat extends DateFormat {
+    private SimpleDateFormat sdf;
+
+    public FooDateFormat(String pattern, Locale loc) {
+        sdf = new SimpleDateFormat(pattern, loc);
+    }
+
+    @Override
+    public StringBuffer format(Date date,
+                               StringBuffer toAppendTo,
+                               FieldPosition fieldPosition) {
+        return sdf.format(date, toAppendTo, fieldPosition);
+    }
+
+    @Override
+    public Date parse(String source, ParsePosition pos) {
+        return sdf.parse(source, pos);
+    }
+
+    @Override
+    public boolean equals(Object other) {
+        return other instanceof FooDateFormat
+            && sdf.equals(((FooDateFormat)other).sdf);
+    }
+
+    @Override
+    public int hashCode() {
+        return sdf.hashCode();
+    }
+}
diff --git a/test/java/util/PluggableLocale/providersrc/FooNumberFormat.java b/test/java/util/PluggableLocale/providersrc/FooNumberFormat.java
new file mode 100644
index 0000000..d13bd73
--- /dev/null
+++ b/test/java/util/PluggableLocale/providersrc/FooNumberFormat.java
@@ -0,0 +1,81 @@
+/*
+ * 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.
+ *
+ * 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.foo;
+
+import java.text.*;
+
+/**
+ * FooNumberFormat provides DecimalFormat methods required for the SPI testing.
+ */
+public class FooNumberFormat extends NumberFormat {
+    private DecimalFormat df;
+
+    public FooNumberFormat(String pattern, DecimalFormatSymbols dfs) {
+        df = new DecimalFormat(pattern, dfs);
+    }
+
+    @Override
+    public StringBuffer format(double number,
+                               StringBuffer toAppendTo,
+                               FieldPosition pos) {
+        return df.format(number, toAppendTo, pos);
+    }
+
+    @Override
+    public StringBuffer format(long number,
+                               StringBuffer toAppendTo,
+                               FieldPosition pos) {
+        return df.format(number, toAppendTo, pos);
+    }
+
+    @Override
+    public Number parse(String source, ParsePosition parsePosition) {
+        return df.parse(source, parsePosition);
+    }
+
+    @Override
+    public boolean equals(Object other) {
+        return other instanceof FooNumberFormat
+            && df.equals(((FooNumberFormat)other).df);
+    }
+
+    @Override
+    public int hashCode() {
+        return df.hashCode();
+    }
+
+    // DecimalFormat specific methods required for testing
+
+    public String toPattern() {
+        return df.toPattern();
+    }
+
+    public DecimalFormatSymbols getDecimalFormatSymbols() {
+        return df.getDecimalFormatSymbols();
+    }
+
+    public void setDecimalSeparatorAlwaysShown(boolean newValue) {
+        df.setDecimalSeparatorAlwaysShown(newValue);
+    }
+}
diff --git a/test/java/util/PluggableLocale/providersrc/Makefile b/test/java/util/PluggableLocale/providersrc/Makefile
index a85ea06..8d2fa9c 100644
--- a/test/java/util/PluggableLocale/providersrc/Makefile
+++ b/test/java/util/PluggableLocale/providersrc/Makefile
@@ -28,6 +28,8 @@
     DateFormatSymbolsProviderImpl.java \
     DecimalFormatSymbolsProviderImpl.java \
     NumberFormatProviderImpl.java \
+    FooDateFormat.java \
+    FooNumberFormat.java \
     Utils.java
 
 BARFILES_JAVA = \
diff --git a/test/java/util/PluggableLocale/providersrc/NumberFormatProviderImpl.java b/test/java/util/PluggableLocale/providersrc/NumberFormatProviderImpl.java
index 164de5e..9aa677c 100644
--- a/test/java/util/PluggableLocale/providersrc/NumberFormatProviderImpl.java
+++ b/test/java/util/PluggableLocale/providersrc/NumberFormatProviderImpl.java
@@ -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
@@ -49,13 +49,15 @@
 
     static String[] patterns = {
         "#,##0.###{0};-#,##0.###{1}", // decimal pattern
+        "#{0};(#){1}", // integer pattern
         "\u00A4#,##0{0};-\u00A4#,##0{1}", // currency pattern
         "#,##0%{0}" // percent pattern
     };
     // Constants used by factory methods to specify a style of format.
     static final int NUMBERSTYLE = 0;
-    static final int CURRENCYSTYLE = 1;
-    static final int PERCENTSTYLE = 2;
+    static final int INTEGERSTYLE = 1;
+    static final int CURRENCYSTYLE = 2;
+    static final int PERCENTSTYLE = 3;
 
     public Locale[] getAvailableLocales() {
         return avail;
@@ -68,10 +70,10 @@
                     MessageFormat.format(patterns[CURRENCYSTYLE],
                                          dialect[i],
                                          dialect[i]);
-                DecimalFormat df = new DecimalFormat(pattern,
+                FooNumberFormat nf = new FooNumberFormat(pattern,
                     DecimalFormatSymbols.getInstance(locale));
-                adjustForCurrencyDefaultFractionDigits(df);
-                return df;
+                adjustForCurrencyDefaultFractionDigits(nf);
+                return nf;
             }
         }
         throw new IllegalArgumentException("locale is not supported: "+locale);
@@ -81,15 +83,15 @@
         for (int i = 0; i < avail.length; i ++) {
             if (Utils.supportsLocale(avail[i], locale)) {
                 String pattern =
-                    MessageFormat.format(patterns[NUMBERSTYLE],
+                    MessageFormat.format(patterns[INTEGERSTYLE],
                                          dialect[i],
                                          dialect[i]);
-                DecimalFormat df = new DecimalFormat(pattern,
+                FooNumberFormat nf = new FooNumberFormat(pattern,
                     DecimalFormatSymbols.getInstance(locale));
-                df.setMaximumFractionDigits(0);
-                df.setDecimalSeparatorAlwaysShown(false);
-                df.setParseIntegerOnly(true);
-                return df;
+                nf.setMaximumFractionDigits(0);
+                nf.setDecimalSeparatorAlwaysShown(false);
+                nf.setParseIntegerOnly(true);
+                return nf;
             }
         }
         throw new IllegalArgumentException("locale is not supported: "+locale);
@@ -102,7 +104,7 @@
                     MessageFormat.format(patterns[NUMBERSTYLE],
                                          dialect[i],
                                          dialect[i]);
-                return new DecimalFormat(pattern,
+                return new FooNumberFormat(pattern,
                     DecimalFormatSymbols.getInstance(locale));
             }
         }
@@ -115,7 +117,7 @@
                 String pattern =
                     MessageFormat.format(patterns[PERCENTSTYLE],
                                          dialect[i]);
-                return new DecimalFormat(pattern,
+                return new FooNumberFormat(pattern,
                     DecimalFormatSymbols.getInstance(locale));
             }
         }
@@ -126,8 +128,8 @@
      * Adjusts the minimum and maximum fraction digits to values that
      * are reasonable for the currency's default fraction digits.
      */
-    void adjustForCurrencyDefaultFractionDigits(DecimalFormat df) {
-        DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
+    void adjustForCurrencyDefaultFractionDigits(FooNumberFormat nf) {
+        DecimalFormatSymbols dfs = nf.getDecimalFormatSymbols();
         Currency currency = dfs.getCurrency();
         if (currency == null) {
             try {
@@ -138,15 +140,15 @@
         if (currency != null) {
             int digits = currency.getDefaultFractionDigits();
             if (digits != -1) {
-                int oldMinDigits = df.getMinimumFractionDigits();
+                int oldMinDigits = nf.getMinimumFractionDigits();
                 // Common patterns are "#.##", "#.00", "#".
                 // Try to adjust all of them in a reasonable way.
-                if (oldMinDigits == df.getMaximumFractionDigits()) {
-                    df.setMinimumFractionDigits(digits);
-                    df.setMaximumFractionDigits(digits);
+                if (oldMinDigits == nf.getMaximumFractionDigits()) {
+                    nf.setMinimumFractionDigits(digits);
+                    nf.setMaximumFractionDigits(digits);
                 } else {
-                    df.setMinimumFractionDigits(Math.min(digits, oldMinDigits));
-                    df.setMaximumFractionDigits(digits);
+                    nf.setMinimumFractionDigits(Math.min(digits, oldMinDigits));
+                    nf.setMaximumFractionDigits(digits);
                 }
             }
         }
diff --git a/test/java/util/Random/DistinctSeeds.java b/test/java/util/Random/DistinctSeeds.java
index 21b653f..7606750 100644
--- a/test/java/util/Random/DistinctSeeds.java
+++ b/test/java/util/Random/DistinctSeeds.java
@@ -59,7 +59,7 @@
             }
         }
         final int threadCount = 2;
-        List<RandomCollector> collectors = new ArrayList<RandomCollector>();
+        List<RandomCollector> collectors = new ArrayList<>();
         List<Thread> threads = new ArrayList<Thread>();
         for (int i = 0; i < threadCount; i++) {
             RandomCollector r = new RandomCollector();
diff --git a/test/java/util/logging/ClassLoaderLeakTest.java b/test/java/util/logging/ClassLoaderLeakTest.java
index 30e6552..bc29876 100644
--- a/test/java/util/logging/ClassLoaderLeakTest.java
+++ b/test/java/util/logging/ClassLoaderLeakTest.java
@@ -89,7 +89,7 @@
 
          MyClassLoader appClassLoader = new MyClassLoader(urls, "test0");
          WeakReference<MyClassLoader> ref =
-                 new WeakReference<MyClassLoader>(appClassLoader);
+                 new WeakReference<>(appClassLoader);
 
 
          Thread appThread = new Thread(appsThreadGroup, launcher, "AppThread-0");
diff --git a/test/java/util/zip/ZipFile/FinalizeZipFile.java b/test/java/util/zip/ZipFile/FinalizeZipFile.java
new file mode 100644
index 0000000..ab89803
--- /dev/null
+++ b/test/java/util/zip/ZipFile/FinalizeZipFile.java
@@ -0,0 +1,100 @@
+/*
+ * 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.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 7007609 7009618
+ * @summary Check that ZipFile objects are always collected
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.util.Random;
+import java.util.zip.*;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+public class FinalizeZipFile {
+
+    private final static CountDownLatch finalizersDone = new CountDownLatch(3);
+
+    private static class InstrumentedZipFile extends ZipFile {
+
+        public InstrumentedZipFile(File f) throws Exception {
+            super(f);
+            System.out.printf("Using %s%n", f.getPath());
+        }
+        protected void finalize() throws IOException {
+            System.out.printf("Killing %s%n", getName());
+            super.finalize();
+            finalizersDone.countDown();
+        }
+    }
+
+    private static void makeGarbage() throws Throwable {
+        final Random rnd = new Random();
+        final String javaHome = System.getProperty("java.home");
+        // Create some ZipFiles.
+        // Find some .jar files in JDK's lib directory.
+        final File lib = new File(javaHome, "lib");
+        check(lib.isDirectory());
+        final File[] jars = lib.listFiles(
+            new FilenameFilter() {
+                public boolean accept(File dir, String name) {
+                    return name.endsWith(".jar");}});
+        check(jars.length > 1);
+
+        new InstrumentedZipFile(jars[rnd.nextInt(jars.length)]).close();
+        new InstrumentedZipFile(jars[rnd.nextInt(jars.length)]).close();
+
+        // Create a ZipFile and get an input stream from it
+        ZipFile zf = new InstrumentedZipFile(jars[rnd.nextInt(jars.length)]);
+        ZipEntry ze = zf.getEntry("META-INF/MANIFEST.MF");
+        InputStream is = zf.getInputStream(ze);
+    }
+
+    public static void realMain(String[] args) throws Throwable {
+        makeGarbage();
+
+        System.gc();
+        finalizersDone.await(5, TimeUnit.SECONDS);
+
+        // Not all ZipFiles were collected?
+        equal(finalizersDone.getCount(), 0L);
+    }
+
+    //--------------------- Infrastructure ---------------------------
+    static volatile int passed = 0, failed = 0;
+    static void pass() {passed++;}
+    static void fail() {failed++; Thread.dumpStack();}
+    static void fail(String msg) {System.out.println(msg); fail();}
+    static void unexpected(Throwable t) {failed++; t.printStackTrace();}
+    static void check(boolean cond) {if (cond) pass(); else fail();}
+    static void equal(Object x, Object y) {
+        if (x == null ? y == null : x.equals(y)) pass();
+        else fail(x + " not equal to " + y);}
+    public static void main(String[] args) throws Throwable {
+        try {realMain(args);} catch (Throwable t) {unexpected(t);}
+        System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
+        if (failed > 0) throw new AssertionError("Some tests failed");}
+}
+
diff --git a/test/javax/script/E4XErrorTest.java b/test/javax/script/E4XErrorTest.java
deleted file mode 100644
index 97eb7aa..0000000
--- a/test/javax/script/E4XErrorTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @bug 6346734 6705893
- * @summary We do *not* support E4X (ECMAScript for XML) in our
- * implementation. We want to throw error on XML literals
- * as early as possible rather than at "runtime" - i.e., when
- * engine looks for "XML" constructor.
- */
-
-import javax.script.*;
-import java.util.Locale;
-
-public class E4XErrorTest {
-
-        public static void main(String[] args) throws Exception {
-            ScriptEngineManager manager = new ScriptEngineManager();
-            ScriptEngine jsengine = Helper.getJsEngine(manager);
-            if (jsengine == null) {
-                System.out.println("Warning: No js engine found; test vacuously passes.");
-                return;
-            }
-
-            // The test below depends on the error message content
-            // that is loaded from resource bundles.  So, we force
-            // English Locale to compare correct value..
-            Locale.setDefault(Locale.US);
-
-            try {
-                jsengine.eval("var v = <html></html>;");
-            } catch (ScriptException se) {
-                String msg = se.getMessage();
-                if (msg.indexOf("syntax error") == -1) {
-                    throw new RuntimeException("syntax error expected, got " +
-                                       msg);
-                }
-                return;
-            }
-            // should not reach here.. exception should have been thrown.
-            throw new RuntimeException("Huh! E4X is supported??");
-        }
-}
diff --git a/test/javax/script/VersionTest.java b/test/javax/script/VersionTest.java
index 13ed9c0..ff28c2c 100644
--- a/test/javax/script/VersionTest.java
+++ b/test/javax/script/VersionTest.java
@@ -32,8 +32,8 @@
 
 public class VersionTest  {
 
-        private static final String JS_LANG_VERSION = "1.6";
-        private static final String JS_ENGINE_VERSION = "1.6 release 2";
+        private static final String JS_LANG_VERSION = "1.8";
+        private static final String JS_ENGINE_VERSION = "1.7 release 3 PRERELEASE";
 
         public static void main(String[] args) throws Exception {
             ScriptEngineManager manager = new ScriptEngineManager();
diff --git a/test/javax/swing/JFileChooser/4847375/bug4847375.java b/test/javax/swing/JFileChooser/4847375/bug4847375.java
new file mode 100644
index 0000000..8a9af80
--- /dev/null
+++ b/test/javax/swing/JFileChooser/4847375/bug4847375.java
@@ -0,0 +1,160 @@
+/*
+ * 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.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 4847375
+ * @summary JFileChooser Create New Folder button is disabled incorrectly
+ * @author Pavel Porvatov
+ */
+
+import sun.awt.OSInfo;
+import sun.awt.shell.ShellFolder;
+
+import javax.swing.*;
+import java.awt.*;
+import java.lang.reflect.Method;
+
+public class bug4847375 {
+    private final String newFolderToolTipText;
+
+    private final String lookAndFeel;
+
+    public static void main(String[] args) throws Exception {
+        if (OSInfo.getOSType() != OSInfo.OSType.WINDOWS) {
+            System.out.println("The test is suitable only for Windows OS. Skipped.");
+
+            return;
+        }
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                new bug4847375("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
+
+                new bug4847375("javax.swing.plaf.metal.MetalLookAndFeel");
+            }
+        });
+    }
+
+    private static Object[][] DIRECTORIES = new Object[][]{
+            {"getDesktop", Boolean.TRUE},
+            {"getDrives", Boolean.FALSE}, // My computer
+            {"getRecent", Boolean.TRUE},
+            {"getNetwork", Boolean.FALSE},
+            {"getPersonal", Boolean.TRUE},
+    };
+
+    private bug4847375(String lookAndFeel) {
+        this.lookAndFeel = lookAndFeel;
+
+        try {
+            UIManager.setLookAndFeel(lookAndFeel);
+        } catch (Exception e) {
+            fail("Cannot set LookAndFeel", e);
+        }
+
+        JFileChooser fileChooser = new JFileChooser();
+
+        // Find button NewFolder
+        newFolderToolTipText = UIManager.getString("FileChooser.newFolderToolTipText", fileChooser.getLocale());
+
+        if (newFolderToolTipText == null || newFolderToolTipText.length() == 0) {
+            fail("Cannot find NewFolderButton in FileChooser (tooltip doesn't exist)");
+
+            return;
+        }
+
+        JButton newFolderButton = findNewFolderButton(fileChooser);
+
+        if (newFolderButton == null) {
+            fail("Cannot find NewFolderButton in FileChooser");
+
+            return;
+        }
+
+        for (Object[] objects : DIRECTORIES) {
+            String getterName = (String) objects[0];
+            Boolean enabledNewFolder = (Boolean) objects[1];
+
+            fileChooser.setCurrentDirectory(getWin32Folder(getterName));
+
+            if (newFolderButton.isEnabled() != enabledNewFolder) {
+                fail("Enabled state of NewFolderButton should be " + enabledNewFolder +
+                        " for Win32ShellFolderManager2." + getterName + "()");
+            }
+        }
+    }
+
+    private JButton findNewFolderButton(Container container) {
+        JButton result = null;
+
+        for (int i = 0; i < container.getComponentCount(); i++) {
+            Component c = container.getComponent(i);
+
+            if (c instanceof JButton && newFolderToolTipText.equals(((JButton) c).getToolTipText())) {
+                if (result != null) {
+                    fail("Two or more NewFolderButton found in FileChooser");
+                }
+
+                result = (JButton) c;
+            }
+
+            if (c instanceof Container) {
+                JButton button = findNewFolderButton((Container) c);
+
+                if (result == null) {
+                    result = button;
+                } else {
+                    if (button != null) {
+                        fail("Two or more NewFolderButton found in FileChooser");
+                    }
+                }
+            }
+        }
+
+        return result;
+    }
+
+    private ShellFolder getWin32Folder(String getterName) {
+        try {
+            Class win32ShellFolderManager2 = Class.forName("sun.awt.shell.Win32ShellFolderManager2");
+
+            Method method = win32ShellFolderManager2.getDeclaredMethod(getterName);
+            method.setAccessible(true);
+
+            return (ShellFolder) method.invoke(null);
+        } catch (Exception e) {
+            fail("Cannot call '" + getterName + "' in the Win32ShellFolderManager2 class", e);
+
+            return null;
+        }
+    }
+
+    private void fail(String s) {
+        throw new RuntimeException("Test failed: " + s);
+    }
+
+    private void fail(String s, Throwable e) {
+        throw new RuntimeException("Test failed for LookAndFeel " + lookAndFeel + ": " + s, e);
+    }
+}
diff --git a/test/javax/swing/JScrollBar/6542335/bug6542335.java b/test/javax/swing/JScrollBar/6542335/bug6542335.java
index 33e95d8..d4ed473 100644
--- a/test/javax/swing/JScrollBar/6542335/bug6542335.java
+++ b/test/javax/swing/JScrollBar/6542335/bug6542335.java
@@ -40,11 +40,13 @@
     private static MyScrollBarUI ui;
 
     public static void main(String[] args) throws Exception {
-        Robot robot = new Robot();
+        final Robot robot = new Robot();
         robot.setAutoDelay(10);
 
         SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
 
+        final Rectangle[] thumbBounds = new Rectangle[1];
+
         SwingUtilities.invokeAndWait(new Runnable() {
             public void run() {
                 final JFrame frame = new JFrame("bug6542335");
@@ -63,25 +65,39 @@
                 rangeModel.setValue(50);
 
                 sb.setModel(rangeModel);
-                frame.add(sb);
+                frame.add(sb, BorderLayout.NORTH);
 
                 frame.setSize(200, 100);
                 frame.setVisible(true);
+
+                thumbBounds[0] = new Rectangle(ui.getThumbBounds());
             }
         });
 
-        Rectangle thumbBounds = new Rectangle(ui.getThumbBounds());
-
-        toolkit.realSync();
-        Point l = sb.getLocationOnScreen();
-        robot.mouseMove(l.x + (int) (0.75 * sb.getWidth()), l.y + sb.getHeight()/2);
-        robot.mousePress(InputEvent.BUTTON1_MASK);
-        robot.mouseRelease(InputEvent.BUTTON1_MASK);
         toolkit.realSync();
 
-        if (!thumbBounds.equals(ui.getThumbBounds())) {
-            throw new RuntimeException("Test failed");
-        }
+        SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                Point l = sb.getLocationOnScreen();
+
+                robot.mouseMove(l.x + (int) (0.75 * sb.getWidth()), l.y + sb.getHeight() / 2);
+                robot.mousePress(InputEvent.BUTTON1_MASK);
+                robot.mouseRelease(InputEvent.BUTTON1_MASK);
+            }
+        });
+
+        toolkit.realSync();
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                Rectangle newThumbBounds = ui.getThumbBounds();
+
+                if (!thumbBounds[0].equals(newThumbBounds)) {
+                    throw new RuntimeException("Test failed.\nOld bounds: " + thumbBounds[0] +
+                    "\nNew bounds: " + newThumbBounds);
+                }
+            }
+        });
     }
 
     static class MyScrollBarUI extends BasicScrollBarUI {
diff --git a/test/javax/swing/JSpinner/6532833/bug6532833.java b/test/javax/swing/JSpinner/6532833/bug6532833.java
new file mode 100644
index 0000000..184fe69
--- /dev/null
+++ b/test/javax/swing/JSpinner/6532833/bug6532833.java
@@ -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.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+   @bug 6532833
+   @summary PIT: Metal LAF - The right side border is not shown for the Spinner after the removing the buttons
+   @author Pavel Porvatov
+*/
+
+import javax.swing.*;
+import java.awt.*;
+
+public class bug6532833 {
+    public static void main(String[] args) throws Exception {
+        SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                JSpinner[] spinners = new JSpinner[2];
+
+                for (int i = 0; i < spinners.length; i++) {
+                    JSpinner spinner = new JSpinner();
+
+                    spinner.setValue(2010);
+
+                    Component arrowUp = spinner.getComponent(0);
+                    Component arrowDown = spinner.getComponent(1);
+
+                    LayoutManager layout = spinner.getLayout();
+
+                    layout.removeLayoutComponent(arrowUp);
+                    layout.removeLayoutComponent(arrowDown);
+
+                    if (i == 1) {
+                        spinner.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
+                    }
+
+                    spinners[i] = spinner;
+                }
+
+                // Do layout of spinners components
+                JFrame frame = new JFrame();
+
+                for (JSpinner spinner : spinners) {
+                    frame.getContentPane().add(spinner);
+                }
+
+                frame.pack();
+
+                for (JSpinner spinner : spinners) {
+                    Insets insets = spinner.getInsets();
+
+                    if (spinner.getWidth() != insets.left + insets.right + spinner.getEditor().getWidth()) {
+                        throw new RuntimeException("Spinner editor width is invalid");
+                    }
+                }
+
+                frame.dispose();
+            }
+        });
+    }
+}
diff --git a/test/javax/swing/SwingWorker/6480289/bug6480289.java b/test/javax/swing/SwingWorker/6480289/bug6480289.java
deleted file mode 100644
index 9ff3496..0000000
--- a/test/javax/swing/SwingWorker/6480289/bug6480289.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/* @test
- *
- * @bug 6480289
- * @author Igor Kushnirskiy
- * @summary tests if consequent workers are executed on the same thread and that VM can exit.
- */
-
-import java.util.*;
-import javax.swing.SwingWorker;
-
-public class bug6480289 {
-    private static final int ITERATIONS = 5;
-    private static final Map<Thread, Integer> threadMap =
-        Collections.synchronizedMap(new HashMap<Thread, Integer>());
-    public static void main(String[] args) throws Exception {
-
-        for (int i = 0; i < ITERATIONS; i++) {
-            if (i != 0) {
-                Thread.sleep(1000 * 5);
-            }
-            SwingWorker<?,?> worker =
-                new SwingWorker<Void, Void>() {
-                    @Override
-                    protected Void doInBackground() {
-                        Integer value = threadMap.get(Thread.currentThread());
-                        value = Integer.valueOf(
-                            ((value == null) ? 0 : value.intValue())
-                            + 1);
-                        threadMap.put(Thread.currentThread(), value);
-                        return null;
-                    }
-                };
-            worker.execute();
-        }
-        if (threadMap.keySet().size() != 1) {
-            throw new RuntimeException("failed. More than one thread.");
-        }
-    }
-}
diff --git a/test/sun/security/krb5/auto/BasicKrb5Test.java b/test/sun/security/krb5/auto/BasicKrb5Test.java
index 1222c7c..aaf6b12 100644
--- a/test/sun/security/krb5/auto/BasicKrb5Test.java
+++ b/test/sun/security/krb5/auto/BasicKrb5Test.java
@@ -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,6 +25,34 @@
  * @test
  * @bug 6706974
  * @summary Add krb5 test infrastructure
+ * @run main/othervm BasicKrb5Test
+ * @run main/othervm BasicKrb5Test des-cbc-crc
+ * @run main/othervm BasicKrb5Test des-cbc-md5
+ * @run main/othervm BasicKrb5Test des3-cbc-sha1
+ * @run main/othervm BasicKrb5Test aes128-cts
+ * @run main/othervm BasicKrb5Test aes256-cts
+ * @run main/othervm BasicKrb5Test rc4-hmac
+ * @run main/othervm BasicKrb5Test -s
+ * @run main/othervm BasicKrb5Test des-cbc-crc -s
+ * @run main/othervm BasicKrb5Test des-cbc-md5 -s
+ * @run main/othervm BasicKrb5Test des3-cbc-sha1 -s
+ * @run main/othervm BasicKrb5Test aes128-cts -s
+ * @run main/othervm BasicKrb5Test aes256-cts -s
+ * @run main/othervm BasicKrb5Test rc4-hmac -s
+ * @run main/othervm BasicKrb5Test -C
+ * @run main/othervm BasicKrb5Test des-cbc-crc -C
+ * @run main/othervm BasicKrb5Test des-cbc-md5 -C
+ * @run main/othervm BasicKrb5Test des3-cbc-sha1 -C
+ * @run main/othervm BasicKrb5Test aes128-cts -C
+ * @run main/othervm BasicKrb5Test aes256-cts -C
+ * @run main/othervm BasicKrb5Test rc4-hmac -C
+ * @run main/othervm BasicKrb5Test -s -C
+ * @run main/othervm BasicKrb5Test des-cbc-crc -s -C
+ * @run main/othervm BasicKrb5Test des-cbc-md5 -s -C
+ * @run main/othervm BasicKrb5Test des3-cbc-sha1 -s -C
+ * @run main/othervm BasicKrb5Test aes128-cts -s -C
+ * @run main/othervm BasicKrb5Test aes256-cts -s -C
+ * @run main/othervm BasicKrb5Test rc4-hmac -s -C
  */
 
 import org.ietf.jgss.GSSName;
@@ -39,6 +67,7 @@
  */
 public class BasicKrb5Test {
 
+    private static boolean conf = true;
     /**
      * @param args empty or etype
      */
@@ -46,8 +75,10 @@
             throws Exception {
 
         String etype = null;
-        if (args.length > 0) {
-            etype = args[0];
+        for (String arg: args) {
+            if (arg.equals("-s")) Context.usingStream = true;
+            else if(arg.equals("-C")) conf = false;
+            else etype = arg;
         }
 
         // Creates and starts the KDC. This line must be put ahead of etype check
@@ -56,8 +87,9 @@
 
         System.out.println("Testing etype " + etype);
         if (etype != null && !EType.isSupported(Config.getInstance().getType(etype))) {
+            // aes256 is not enabled on all systems
             System.out.println("Not supported.");
-            System.exit(0);
+            return;
         }
 
         new BasicKrb5Test().go(OneKDC.SERVER, OneKDC.BACKEND);
@@ -71,6 +103,7 @@
 
         c.startAsClient(server, GSSUtil.GSS_KRB5_MECH_OID);
         c.x().requestCredDeleg(true);
+        c.x().requestConf(conf);
         s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
 
         c.status();
@@ -90,6 +123,7 @@
         s = null;
 
         s2.startAsClient(backend, GSSUtil.GSS_KRB5_MECH_OID);
+        s2.x().requestConf(conf);
         b.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
 
         s2.status();
diff --git a/test/sun/security/krb5/auto/Context.java b/test/sun/security/krb5/auto/Context.java
index e72c495..86726e3 100644
--- a/test/sun/security/krb5/auto/Context.java
+++ b/test/sun/security/krb5/auto/Context.java
@@ -42,7 +42,8 @@
 import com.sun.security.jgss.ExtendedGSSContext;
 import com.sun.security.jgss.InquireType;
 import com.sun.security.jgss.AuthorizationDataEntry;
-import java.io.File;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
 
 /**
  * Context of a JGSS subject, encapsulating Subject and GSSContext.
@@ -78,6 +79,8 @@
     private String name;
     private GSSCredential cred;     // see static method delegated().
 
+    static boolean usingStream = false;
+
     private Context() {}
 
     /**
@@ -365,7 +368,14 @@
             public byte[] run(Context me, byte[] dummy) throws Exception {
                 System.out.println("wrap");
                 MessageProp p1 = new MessageProp(0, true);
-                byte[] out = me.x.wrap(messageBytes, 0, messageBytes.length, p1);
+                byte[] out;
+                if (usingStream) {
+                    ByteArrayOutputStream os = new ByteArrayOutputStream();
+                    me.x.wrap(new ByteArrayInputStream(messageBytes), os, p1);
+                    out = os.toByteArray();
+                } else {
+                    out = me.x.wrap(messageBytes, 0, messageBytes.length, p1);
+                }
                 System.out.println(printProp(p1));
                 return out;
             }
@@ -375,27 +385,46 @@
             @Override
             public byte[] run(Context me, byte[] input) throws Exception {
                 MessageProp p1 = new MessageProp(0, true);
-                byte[] bytes = me.x.unwrap(input, 0, input.length, p1);
+                byte[] bytes;
+                if (usingStream) {
+                    ByteArrayOutputStream os = new ByteArrayOutputStream();
+                    me.x.unwrap(new ByteArrayInputStream(input), os, p1);
+                    bytes = os.toByteArray();
+                } else {
+                    bytes = me.x.unwrap(input, 0, input.length, p1);
+                }
                 if (!Arrays.equals(messageBytes, bytes))
                     throw new Exception("wrap/unwrap mismatch");
                 System.out.println("unwrap");
                 System.out.println(printProp(p1));
                 p1 = new MessageProp(0, true);
                 System.out.println("getMIC");
-                bytes = me.x.getMIC(bytes, 0, bytes.length, p1);
+                if (usingStream) {
+                    ByteArrayOutputStream os = new ByteArrayOutputStream();
+                    me.x.getMIC(new ByteArrayInputStream(messageBytes), os, p1);
+                    bytes = os.toByteArray();
+                } else {
+                    bytes = me.x.getMIC(messageBytes, 0, messageBytes.length, p1);
+                }
                 System.out.println(printProp(p1));
                 return bytes;
             }
         }, t);
+
         // Re-unwrap should make p2.isDuplicateToken() returns true
         s1.doAs(new Action() {
             @Override
             public byte[] run(Context me, byte[] input) throws Exception {
                 MessageProp p1 = new MessageProp(0, true);
                 System.out.println("verifyMIC");
-                me.x.verifyMIC(input, 0, input.length,
-                        messageBytes, 0, messageBytes.length,
-                        p1);
+                if (usingStream) {
+                    me.x.verifyMIC(new ByteArrayInputStream(input),
+                            new ByteArrayInputStream(messageBytes), p1);
+                } else {
+                    me.x.verifyMIC(input, 0, input.length,
+                            messageBytes, 0, messageBytes.length,
+                            p1);
+                }
                 System.out.println(printProp(p1));
                 return null;
             }
@@ -416,7 +445,9 @@
         sb.append(prop.isGapToken()?"gap, ":"");
         sb.append(prop.isOldToken()?"old, ":"");
         sb.append(prop.isUnseqToken()?"unseq, ":"");
-        sb.append(prop.getMinorString()+ "(" + prop.getMinorStatus()+")");
+        if (prop.getMinorStatus() != 0) {
+            sb.append(prop.getMinorString()+ "(" + prop.getMinorStatus()+")");
+        }
         return sb.toString();
     }
 
@@ -442,7 +473,13 @@
                         return null;
                     } else {
                         System.out.println(c.name + " call initSecContext");
-                        return me.x.initSecContext(input, 0, input.length);
+                        if (usingStream) {
+                            ByteArrayOutputStream os = new ByteArrayOutputStream();
+                            me.x.initSecContext(new ByteArrayInputStream(input), os);
+                            return os.size() == 0 ? null : os.toByteArray();
+                        } else {
+                            return me.x.initSecContext(input, 0, input.length);
+                        }
                     }
                 }
             }, t);
@@ -460,7 +497,13 @@
                         return null;
                     } else {
                         System.out.println(s.name + " called acceptSecContext");
-                        return me.x.acceptSecContext(input, 0, input.length);
+                        if (usingStream) {
+                            ByteArrayOutputStream os = new ByteArrayOutputStream();
+                            me.x.acceptSecContext(new ByteArrayInputStream(input), os);
+                            return os.size() == 0 ? null : os.toByteArray();
+                        } else {
+                            return me.x.acceptSecContext(input, 0, input.length);
+                        }
                     }
                 }
             }, t);
diff --git a/test/sun/security/krb5/auto/basic.sh b/test/sun/security/krb5/auto/basic.sh
deleted file mode 100644
index a3aa3ce..0000000
--- a/test/sun/security/krb5/auto/basic.sh
+++ /dev/null
@@ -1,75 +0,0 @@
-#
-# Copyright (c) 2008, 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.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 6706974
-# @summary Add krb5 test infrastructure
-# @run shell/timeout=300 basic.sh
-#
-
-if [ "${TESTSRC}" = "" ] ; then
-  TESTSRC="."
-fi
-if [ "${TESTJAVA}" = "" ] ; then
-  echo "TESTJAVA not set.  Test cannot execute."
-  echo "FAILED!!!"
-  exit 1
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
-  Windows_* )
-    FS="\\"
-    SEP=";"
-    ;;
-  CYGWIN* )
-    FS="/"
-    SEP=";"
-    ;;
-  * )
-    FS="/"
-    SEP=":"
-    ;;
-esac
-
-${TESTJAVA}${FS}bin${FS}javac -XDignore.symbol.file -d . \
-    ${TESTSRC}${FS}BasicKrb5Test.java \
-    ${TESTSRC}${FS}KDC.java \
-    ${TESTSRC}${FS}OneKDC.java \
-    ${TESTSRC}${FS}Action.java \
-    ${TESTSRC}${FS}Context.java \
-    || exit 10
-
-# Add $TESTSRC to classpath so that customized nameservice can be used
-J="${TESTJAVA}${FS}bin${FS}java -cp $TESTSRC${SEP}. BasicKrb5Test"
-
-$J || exit 100
-$J des-cbc-crc || exit 1
-$J des-cbc-md5 || exit 3
-$J des3-cbc-sha1 || exit 16
-$J aes128-cts || exit 17
-$J aes256-cts || exit 18
-$J rc4-hmac || exit 23
-
-exit 0
diff --git a/test/sun/security/pkcs11/Provider/ConfigShortPath.java b/test/sun/security/pkcs11/Provider/ConfigShortPath.java
new file mode 100644
index 0000000..daa1ab3
--- /dev/null
+++ b/test/sun/security/pkcs11/Provider/ConfigShortPath.java
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/**
+ * @test
+ * @bug 6581254
+ * @summary Allow "~" in config to support windows short path
+ * @author Valerie Peng
+ */
+
+import java.security.*;
+import java.io.*;
+
+public class ConfigShortPath {
+
+    public static void main(String[] args) {
+        String testSrc = System.getProperty("test.src", ".");
+        String configFile = testSrc + File.separator + "csp.cfg";
+        System.out.println("Testing against " + configFile);
+        try {
+            Provider p = new sun.security.pkcs11.SunPKCS11(configFile);
+        } catch (ProviderException pe) {
+            String cause = pe.getCause().getMessage();
+            if (cause.indexOf("Unexpected token") != -1) {
+                // re-throw to indicate test failure
+                throw pe;
+            }
+        }
+    }
+}
diff --git a/test/sun/security/pkcs11/Provider/csp.cfg b/test/sun/security/pkcs11/Provider/csp.cfg
new file mode 100644
index 0000000..9cd8962
--- /dev/null
+++ b/test/sun/security/pkcs11/Provider/csp.cfg
@@ -0,0 +1,4 @@
+showInfo = false 
+name = NSSTrust 
+nssSecmodDirectory = C:/DOCUME~1/dtftest/LOCALS~1/Temp/Work/exec/jsn_7.0_int-7.0_nightly_sec_win_32_part2-2007-07-16-09-06-04-0209/dtftest.Windows_2003.x86/NSS//db
+nssLibraryDirectory = Y:/xml/CC_DTF/knight_ws/suites/jsn_7.0_int/security/tools/lib/nss/WINNT/ 
diff --git a/test/sun/tools/jstat/gcNewCapacityOutput1.awk b/test/sun/tools/jstat/gcNewCapacityOutput1.awk
index b0587b7..0491fa5 100644
--- a/test/sun/tools/jstat/gcNewCapacityOutput1.awk
+++ b/test/sun/tools/jstat/gcNewCapacityOutput1.awk
@@ -4,7 +4,7 @@
 # specific values.
 #
 #  NGCMN      NGCMX       NGC      S0CMX     S0C     S1CMX     S1C       ECMX        EC      YGC   FGC 
-#    2176.0     7232.0     2176.0     64.0    192.0    192.0     64.0     6848.0     2048.0     1     0
+#    2176.0     7232.0     2176.0    192.0     64.0    192.0     64.0     6848.0     2048.0     1     0
 
 
 BEGIN	{
diff --git a/test/tools/launcher/Settings.java b/test/tools/launcher/Settings.java
index b78443a..10511bf 100644
--- a/test/tools/launcher/Settings.java
+++ b/test/tools/launcher/Settings.java
@@ -74,8 +74,15 @@
 
     static void runTestOptionDefault() throws IOException {
         TestHelper.TestResult tr = null;
-        tr = TestHelper.doExec(TestHelper.javaCmd, "-Xmx512m", "-Xss128k",
-                "-XshowSettings", "-jar", testJar.getAbsolutePath());
+        tr = TestHelper.doExec(TestHelper.javaCmd, "-Xms64m", "-Xmx512m",
+                "-Xss128k", "-XshowSettings", "-jar", testJar.getAbsolutePath());
+        containsAllOptions(tr);
+        if (!tr.isOK()) {
+            System.out.println(tr.status);
+            throw new RuntimeException("test fails");
+        }
+        tr = TestHelper.doExec(TestHelper.javaCmd, "-Xms65536k", "-Xmx712m",
+                "-Xss122880", "-XshowSettings", "-jar", testJar.getAbsolutePath());
         containsAllOptions(tr);
         if (!tr.isOK()) {
             System.out.println(tr.status);
diff --git a/test/tools/pack200/T7007157.java b/test/tools/pack200/T7007157.java
new file mode 100644
index 0000000..72f8792
--- /dev/null
+++ b/test/tools/pack200/T7007157.java
@@ -0,0 +1,67 @@
+/*
+ * 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.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Map;
+import java.util.jar.JarFile;
+import java.util.jar.Pack200;
+/*
+ * @test
+ * @bug 7007157
+ * @summary make sure the strip command works on an attribute
+ * @compile -XDignore.symbol.file Utils.java T7007157.java
+ * @run main T7007157
+ * @author ksrini
+ */
+public class T7007157 {
+
+    public static void main(String... args) throws IOException {
+        File sdkHome = Utils.JavaSDK;
+        File testJar = new File(new File(sdkHome, "lib"), "tools.jar");
+        JarFile jarFile = new JarFile(testJar);
+        File packFile = new File("foo.pack");
+        Pack200.Packer packer = Pack200.newPacker();
+        Map<String, String> p = packer.properties();
+        // Take the time optimization vs. space
+        p.put(packer.EFFORT, "1");  // CAUTION: do not use 0.
+        // Make the memory consumption as effective as possible
+        p.put(packer.SEGMENT_LIMIT, "10000");
+        // ignore all JAR deflation requests to save time
+        p.put(packer.DEFLATE_HINT, packer.FALSE);
+        // save the file ordering of the original JAR
+        p.put(packer.KEEP_FILE_ORDER, packer.TRUE);
+        // strip the StackMapTables
+        p.put(packer.CODE_ATTRIBUTE_PFX + "StackMapTable", packer.STRIP);
+        FileOutputStream fos = null;
+        try {
+            // Write out to a jtreg scratch area
+            fos = new FileOutputStream(packFile);
+            // Call the packer
+            packer.pack(jarFile, fos);
+        } finally {
+            Utils.close(fos);
+            Utils.close(jarFile);
+        }
+    }
+}