changeset 5888:d94613ac03d8 jdk8-b58

Merge
author katleman
date Wed, 26 Sep 2012 22:22:51 -0700
parents c9568c94c4e7 (current diff) 4015dec20965 (diff)
children abad1f417bd3 5aff878baaf6 4b8bb77fdda9 77bf5cde2192
files src/macosx/classes/sun/awt/SunToolkitSubclass.java src/share/classes/sun/management/LockDataConverter.java src/share/classes/sun/management/LockDataConverterMXBean.java src/share/classes/sun/security/x509/CertificateIssuerUniqueIdentity.java src/share/classes/sun/security/x509/CertificateSubjectUniqueIdentity.java test/sun/misc/URLClassPath/ClassnameCharTest.sh test/sun/net/www/httptest/HttpServer.java test/sun/security/ssl/sun/net/www/httpstest/HttpServer.java
diffstat 164 files changed, 6636 insertions(+), 3215 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Fri Sep 21 12:22:52 2012 -0700
+++ b/.hgtags	Wed Sep 26 22:22:51 2012 -0700
@@ -178,3 +178,4 @@
 70ad0ed1d6cef0e7712690d1bab21e4769708aad jdk8-b54
 1f3f4b333341873f00da3dee85e4879f0e89c9bb jdk8-b55
 2e9eeef2909b33c9224a024afddb61ccb0b77f14 jdk8-b56
+51594d095a4bcffac4a314bf6e148214501399e0 jdk8-b57
--- a/src/macosx/classes/sun/awt/SunToolkitSubclass.java	Fri Sep 21 12:22:52 2012 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.awt;
-
-// This class exists only so we can flush the PostEventQueue for the right AppContext
-// The default flushPendingEvents only flushes the thread-local context, which is wrong.
-// c.f. 3746956
-public abstract class SunToolkitSubclass extends SunToolkit {
-    public static void flushPendingEvents(AppContext appContext) {
-        flushLock.lock();
-        PostEventQueue postEventQueue = (PostEventQueue)appContext.get("PostEventQueue");
-        if (postEventQueue != null) {
-            postEventQueue.flush();
-        }
-        flushLock.unlock();
-    }
-}
--- a/src/macosx/classes/sun/font/CFontManager.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/macosx/classes/sun/font/CFontManager.java	Wed Sep 26 22:22:51 2012 -0700
@@ -37,6 +37,7 @@
 import javax.swing.plaf.FontUIResource;
 
 import sun.awt.FontConfiguration;
+import sun.awt.HeadlessToolkit;
 import sun.lwawt.macosx.*;
 
 public class CFontManager extends SunFontManager {
@@ -342,9 +343,14 @@
     @Override
     public String getFontPath(boolean noType1Fonts) {
         // In the case of the Cocoa toolkit, since we go through NSFont, we dont need to register /Library/Fonts
-        if (Toolkit.getDefaultToolkit() instanceof LWCToolkit) {
+        Toolkit tk = Toolkit.getDefaultToolkit();
+        if (tk instanceof HeadlessToolkit) {
+            tk = ((HeadlessToolkit)tk).getUnderlyingToolkit();
+        }
+        if (tk instanceof LWCToolkit) {
             return "";
         }
+
         // X11 case
         return "/Library/Fonts";
     }
--- a/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java	Wed Sep 26 22:22:51 2012 -0700
@@ -134,7 +134,7 @@
         boolean postsTyped = false;
 
         char testChar = KeyEvent.CHAR_UNDEFINED;
-        char testDeadChar = 0;
+        boolean isDeadChar = (chars!= null && chars.length() == 0);
 
         if (isFlagsChangedEvent) {
             int[] in = new int[] {modifierFlags, keyCode};
@@ -150,14 +150,18 @@
                 testChar = chars.charAt(0);
             }
 
-            int[] in = new int[] {testChar, testDeadChar, modifierFlags, keyCode};
-            int[] out = new int[2]; // [jkeyCode, jkeyLocation]
+            int[] in = new int[] {testChar, isDeadChar ? 1 : 0, modifierFlags, keyCode};
+            int[] out = new int[3]; // [jkeyCode, jkeyLocation, deadChar]
 
             postsTyped = NSEvent.nsToJavaKeyInfo(in, out);
             if (!postsTyped) {
                 testChar = KeyEvent.CHAR_UNDEFINED;
             }
 
+            if(isDeadChar){
+                testChar = (char) out[2];
+            }
+
             jkeyCode = out[0];
             jkeyLocation = out[1];
             jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
--- a/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java	Wed Sep 26 22:22:51 2012 -0700
@@ -536,7 +536,7 @@
             SunToolkit.postEvent(appContext, invocationEvent);
 
             // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock
-            sun.awt.SunToolkitSubclass.flushPendingEvents(appContext);
+            SunToolkit.flushPendingEvents(appContext);
         } else {
             // This should be the equivalent to EventQueue.invokeAndWait
             ((LWCToolkit)Toolkit.getDefaultToolkit()).getSystemEventQueueForInvokeAndWait().postEvent(invocationEvent);
@@ -561,7 +561,7 @@
             SunToolkit.postEvent(appContext, invocationEvent);
 
             // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock
-            sun.awt.SunToolkitSubclass.flushPendingEvents(appContext);
+            SunToolkit.flushPendingEvents(appContext);
         } else {
             // This should be the equivalent to EventQueue.invokeAndWait
             ((LWCToolkit)Toolkit.getDefaultToolkit()).getSystemEventQueueForInvokeAndWait().postEvent(invocationEvent);
--- a/src/macosx/native/sun/awt/AWTEvent.h	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/macosx/native/sun/awt/AWTEvent.h	Wed Sep 26 22:22:51 2012 -0700
@@ -33,5 +33,7 @@
 void DeliverJavaMouseEvent(JNIEnv *env, NSEvent *event, jobject peer);
 void SendAdditionalJavaEvents(JNIEnv *env, NSEvent *nsEvent, jobject peer);
 jint GetJavaMouseModifiers(NSInteger button, NSUInteger modifierFlags);
+jint NsKeyModifiersToJavaModifiers(NSUInteger nsFlags, BOOL isExtMods);
+NSUInteger JavaModifiersToNsKeyModifiers(jint javaModifiers, BOOL isExtMods);
 
 #endif /* __AWTEVENT_H */
--- a/src/macosx/native/sun/awt/AWTEvent.m	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/macosx/native/sun/awt/AWTEvent.m	Wed Sep 26 22:22:51 2012 -0700
@@ -26,6 +26,7 @@
 #import <JavaNativeFoundation/JavaNativeFoundation.h>
 #import <JavaRuntimeSupport/JavaRuntimeSupport.h>
 #import <sys/time.h>
+#include <Carbon/Carbon.h>
 
 #import "LWCToolkit.h"
 #import "ThreadUtilities.h"
@@ -244,6 +245,7 @@
     //NSUInteger cgsRightMask;
     unsigned short leftKeyCode;
     unsigned short rightKeyCode;
+    jint javaExtMask;
     jint javaMask;
     jint javaKey;
 }
@@ -254,6 +256,7 @@
         0,
         0,
         0, // no Java equivalent
+        0, // no Java equivalent
         java_awt_event_KeyEvent_VK_CAPS_LOCK
     },
     {
@@ -263,6 +266,7 @@
         56,
         60,
         java_awt_event_InputEvent_SHIFT_DOWN_MASK,
+        java_awt_event_InputEvent_SHIFT_MASK,
         java_awt_event_KeyEvent_VK_SHIFT
     },
     {
@@ -272,6 +276,7 @@
         59,
         62,
         java_awt_event_InputEvent_CTRL_DOWN_MASK,
+        java_awt_event_InputEvent_CTRL_MASK,
         java_awt_event_KeyEvent_VK_CONTROL
     },
     {
@@ -281,6 +286,7 @@
         58,
         61,
         java_awt_event_InputEvent_ALT_DOWN_MASK,
+        java_awt_event_InputEvent_ALT_MASK,
         java_awt_event_KeyEvent_VK_ALT
     },
     {
@@ -290,6 +296,7 @@
         55,
         54,
         java_awt_event_InputEvent_META_DOWN_MASK,
+        java_awt_event_InputEvent_META_MASK,
         java_awt_event_KeyEvent_VK_META
     },
     // NSNumericPadKeyMask
@@ -298,10 +305,11 @@
         0,
         0,
         0, // no Java equivalent
+        0, // no Java equivalent
         java_awt_event_KeyEvent_VK_HELP
     },
     // NSFunctionKeyMask
-    {0, 0, 0, 0, 0}
+    {0, 0, 0, 0, 0, 0}
 };
 
 /*
@@ -371,26 +379,67 @@
     return nsChar;
 }
 
+static unichar NsGetDeadKeyChar(unsigned short keyCode)
+{
+    TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
+    CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
+    const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
+    // Carbon modifiers should be used instead of NSEvent modifiers
+    UInt32 modifierKeyState = (GetCurrentEventKeyModifiers() >> 8) & 0xFF;
+
+    if (keyboardLayout) {
+        UInt32 deadKeyState = 0;
+        UniCharCount maxStringLength = 255;
+        UniCharCount actualStringLength = 0;
+        UniChar unicodeString[maxStringLength];
+
+        // get the deadKeyState
+        OSStatus status = UCKeyTranslate(keyboardLayout,
+                                         keyCode, kUCKeyActionDown, modifierKeyState,
+                                         LMGetKbdType(), kUCKeyTranslateNoDeadKeysBit,
+                                         &deadKeyState,
+                                         maxStringLength,
+                                         &actualStringLength, unicodeString);
+
+        if (status == noErr && deadKeyState != 0) {
+            // Press SPACE to get the dead key char
+            status = UCKeyTranslate(keyboardLayout,
+                                    kVK_Space, kUCKeyActionDown, 0,
+                                    LMGetKbdType(), 0,
+                                    &deadKeyState,
+                                    maxStringLength,
+                                    &actualStringLength, unicodeString);
+
+            if (status == noErr && actualStringLength > 0) {
+                return unicodeString[0];
+            }
+        }
+    }
+    return 0;
+}
+
 /*
  * This is the function that uses the table above to take incoming
  * NSEvent keyCodes and translate to the Java virtual key code.
  */
 static void
-NsCharToJavaVirtualKeyCode(unichar ch, unichar deadChar,
+NsCharToJavaVirtualKeyCode(unichar ch, BOOL isDeadChar,
                            NSUInteger flags, unsigned short key,
-                           jint *keyCode, jint *keyLocation, BOOL *postsTyped)
+                           jint *keyCode, jint *keyLocation, BOOL *postsTyped, unichar *deadChar)
 {
     static size_t size = sizeof(keyTable) / sizeof(struct _key);
     NSInteger offset;
 
-    if (deadChar) {
+    if (isDeadChar) {
+        unichar testDeadChar = NsGetDeadKeyChar(key);
         const struct CharToVKEntry *map;
         for (map = charToDeadVKTable; map->c != 0; ++map) {
-            if (deadChar == map->c) {
+            if (testDeadChar == map->c) {
                 *keyCode = map->javaKey;
                 *postsTyped = NO;
                 // TODO: use UNKNOWN here?
                 *keyLocation = java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN;
+                *deadChar = testDeadChar;
                 return;
             }
         }
@@ -491,25 +540,51 @@
 /*
  * This returns the java modifiers for a key NSEvent.
  */
-static jint
-NsKeyModifiersToJavaModifiers(NSUInteger nsFlags)
+jint NsKeyModifiersToJavaModifiers(NSUInteger nsFlags, BOOL isExtMods)
 {
     jint javaModifiers = 0;
     const struct _nsKeyToJavaModifier* cur;
 
     for (cur = nsKeyToJavaModifierTable; cur->nsMask != 0; ++cur) {
         if ((cur->nsMask & nsFlags) != 0) {
-            javaModifiers |= cur->javaMask;
+            javaModifiers |= isExtMods? cur->javaExtMask : cur->javaMask;
         }
     }
 
     return javaModifiers;
 }
 
+/*
+ * This returns the NSEvent flags for java key modifiers.
+ */
+NSUInteger JavaModifiersToNsKeyModifiers(jint javaModifiers, BOOL isExtMods)
+{
+    NSUInteger nsFlags = 0;
+    const struct _nsKeyToJavaModifier* cur;
+
+    for (cur = nsKeyToJavaModifierTable; cur->nsMask != 0; ++cur) {
+        jint mask = isExtMods? cur->javaExtMask : cur->javaMask; 
+        if ((mask & javaModifiers) != 0) {
+            nsFlags |= cur->nsMask;
+        }
+    }
+
+    // special case
+    jint mask = isExtMods? java_awt_event_InputEvent_ALT_GRAPH_DOWN_MASK : 
+                           java_awt_event_InputEvent_ALT_GRAPH_MASK;
+
+    if ((mask & javaModifiers) != 0) {
+        nsFlags |= NSAlternateKeyMask;      
+    }
+
+    return nsFlags;
+}
+
+
 jint GetJavaMouseModifiers(NSInteger button, NSUInteger modifierFlags)
 {
     // Mousing needs the key modifiers
-    jint modifiers = NsKeyModifiersToJavaModifiers(modifierFlags);
+    jint modifiers = NsKeyModifiersToJavaModifiers(modifierFlags, YES);
 
 
     /*
@@ -590,7 +665,7 @@
 
 JNF_COCOA_ENTER(env);
 
-    jmodifiers = NsKeyModifiersToJavaModifiers(modifierFlags);
+    jmodifiers = NsKeyModifiersToJavaModifiers(modifierFlags, YES);
 
 JNF_COCOA_EXIT(env);
 
@@ -615,20 +690,22 @@
 
     // in  = [testChar, testDeadChar, modifierFlags, keyCode]
     jchar testChar = (jchar)data[0];
-    jchar testDeadChar = (jchar)data[1];
+    BOOL isDeadChar = (data[1] != 0);
     jint modifierFlags = data[2];
     jshort keyCode = (jshort)data[3];
 
     jint jkeyCode = java_awt_event_KeyEvent_VK_UNDEFINED;
     jint jkeyLocation = java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN;
+    jchar testDeadChar = 0;
 
-    NsCharToJavaVirtualKeyCode((unichar)testChar, (unichar)testDeadChar,
+    NsCharToJavaVirtualKeyCode((unichar)testChar, isDeadChar,
                                (NSUInteger)modifierFlags, (unsigned short)keyCode,
-                               &jkeyCode, &jkeyLocation, &postsTyped);
+                               &jkeyCode, &jkeyLocation, &postsTyped, &testDeadChar);
 
     // out = [jkeyCode, jkeyLocation];
     (*env)->SetIntArrayRegion(env, outData, 0, 1, &jkeyCode);
     (*env)->SetIntArrayRegion(env, outData, 1, 1, &jkeyLocation);
+    (*env)->SetIntArrayRegion(env, outData, 2, 1, (jint *)&testDeadChar);
 
     (*env)->ReleaseIntArrayElements(env, inData, data, 0);
 
@@ -685,12 +762,12 @@
 (JNIEnv *env, jclass cls, char nsChar, jint modifierFlags)
 {
     jchar javaChar = 0;
-    
+
 JNF_COCOA_ENTER(env);
-    
+
     javaChar = NsCharToJavaChar(nsChar, modifierFlags);
 
 JNF_COCOA_EXIT(env);
-    
+
     return javaChar;
 }
--- a/src/macosx/native/sun/awt/AWTWindow.m	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/macosx/native/sun/awt/AWTWindow.m	Wed Sep 26 22:22:51 2012 -0700
@@ -178,8 +178,8 @@
         [self.nsWindow setDocumentEdited:IS(bits, DOCUMENT_MODIFIED)];
     }
 
-    if ([self.nsWindow respondsToSelector:@selector(toggleFullScreen:)]) {
-        if (IS(mask, FULLSCREENABLE)) {
+    if (IS(mask, FULLSCREENABLE) && [self.nsWindow respondsToSelector:@selector(toggleFullScreen:)]) {
+        if (IS(bits, FULLSCREENABLE)) {
             [self.nsWindow setCollectionBehavior:(1 << 7) /*NSWindowCollectionBehaviorFullScreenPrimary*/];
         } else {
             [self.nsWindow setCollectionBehavior:NSWindowCollectionBehaviorDefault];
--- a/src/macosx/native/sun/awt/CDragSource.m	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/macosx/native/sun/awt/CDragSource.m	Wed Sep 26 22:22:51 2012 -0700
@@ -460,7 +460,7 @@
     }
 
     // Convert fModifiers (extModifiers) to NS:
-    NSUInteger modifiers = [DnDUtilities mapJavaExtModifiersToNSKeyModifiers:fModifiers];
+    NSUInteger modifiers = JavaModifiersToNsKeyModifiers(fModifiers, TRUE); 
 
     // Just a dummy value ...
     NSInteger eventNumber = 0;
@@ -658,7 +658,7 @@
     }
 
     // b) drag actions (key modifiers) have changed:
-    jint modifiers = [DnDUtilities currentJavaExtKeyModifiers];
+    jint modifiers = NsKeyModifiersToJavaModifiers([NSEvent modifierFlags], YES);
     if (fDragKeyModifiers != modifiers) {
         NSDragOperation currentOp = [DnDUtilities nsDragOperationForModifiers:[NSEvent modifierFlags]];
         NSDragOperation allowedOp = [DnDUtilities mapJavaDragOperationToNS:fSourceActions] & currentOp;
--- a/src/macosx/native/sun/awt/CMenuItem.m	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/macosx/native/sun/awt/CMenuItem.m	Wed Sep 26 22:22:51 2012 -0700
@@ -70,6 +70,18 @@
     JNIEnv *env = [ThreadUtilities getJNIEnv];
 JNF_COCOA_ENTER(env);
 
+    // If we are called as a result of user pressing a shorcut, do nothing,
+    // because AVTView has already sent corresponding key event to the Java 
+    // layer from performKeyEquivalent
+    NSEvent *currEvent = [[NSApplication sharedApplication] currentEvent];
+    if ([currEvent type] == NSKeyDown) {
+        NSString *menuKey = [sender keyEquivalent];
+        NSString *eventKey = [currEvent characters];
+        if ([menuKey isEqualToString:eventKey]) {
+            return;
+        }
+    }
+
     if (fIsCheckbox) {
         static JNF_CLASS_CACHE(jc_CCheckboxMenuItem, "sun/lwawt/macosx/CCheckboxMenuItem");
         static JNF_MEMBER_CACHE(jm_ckHandleAction, jc_CCheckboxMenuItem, "handleAction", "(Z)V");
@@ -83,14 +95,8 @@
         static JNF_CLASS_CACHE(jc_CMenuItem, "sun/lwawt/macosx/CMenuItem");
         static JNF_MEMBER_CACHE(jm_handleAction, jc_CMenuItem, "handleAction", "(JI)V"); // AWT_THREADING Safe (event)
 
-        NSEvent *currEvent = [[NSApplication sharedApplication] currentEvent];
         NSUInteger modifiers = [currEvent modifierFlags];
-        jint javaModifiers = 0;
-
-        if ((modifiers & NSCommandKeyMask) != 0)   javaModifiers |= java_awt_Event_META_MASK;
-        if ((modifiers & NSShiftKeyMask) != 0)     javaModifiers |= java_awt_Event_SHIFT_MASK;
-        if ((modifiers & NSControlKeyMask) != 0)   javaModifiers |= java_awt_Event_CTRL_MASK;
-        if ((modifiers & NSAlternateKeyMask) != 0) javaModifiers |= java_awt_Event_ALT_MASK;
+        jint javaModifiers = NsKeyModifiersToJavaModifiers(modifiers, NO);
 
         JNFCallVoidMethod(env, fPeer, jm_handleAction, UTC(currEvent), javaModifiers); // AWT_THREADING Safe (event)
     }
@@ -117,10 +123,7 @@
             modifiers &= ~java_awt_event_KeyEvent_SHIFT_MASK;
         }
 
-        if ((modifiers & java_awt_event_KeyEvent_SHIFT_MASK) != 0) modifierMask |= NSShiftKeyMask;
-        if ((modifiers & java_awt_event_KeyEvent_CTRL_MASK) != 0)  modifierMask |= NSControlKeyMask;
-        if ((modifiers & java_awt_event_KeyEvent_ALT_MASK) != 0)   modifierMask |= NSAlternateKeyMask;
-        if ((modifiers & java_awt_event_KeyEvent_META_MASK) != 0)  modifierMask |= NSCommandKeyMask;
+        modifierMask = JavaModifiersToNsKeyModifiers(modifiers, NO);
     }
 
     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
--- a/src/macosx/native/sun/awt/CTextPipe.m	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/macosx/native/sun/awt/CTextPipe.m	Wed Sep 26 22:22:51 2012 -0700
@@ -239,9 +239,22 @@
     CGContextSetTextMatrix(cgRef, CGAffineTransformIdentity); // resets the damage from CoreText
 
     NSString *string = [NSString stringWithCharacters:chars length:length];
+    /*
+       The calls below were used previously but for unknown reason did not 
+       render using the right font (see bug 7183516) when attribString is not 
+       initialized with font dictionary attributes.  It seems that "options" 
+       in CTTypesetterCreateWithAttributedStringAndOptions which contains the 
+       font dictionary is ignored.
+
     NSAttributedString *attribString = [[NSAttributedString alloc] initWithString:string];
 
     CTTypesetterRef typeSetterRef = CTTypesetterCreateWithAttributedStringAndOptions((CFAttributedStringRef) attribString, (CFDictionaryRef) ctsDictionaryFor(nsFont, JRSFontStyleUsesFractionalMetrics(strike->fStyle)));
+    */
+    NSAttributedString *attribString = [[NSAttributedString alloc]
+        initWithString:string
+        attributes:ctsDictionaryFor(nsFont, JRSFontStyleUsesFractionalMetrics(strike->fStyle))];
+    
+    CTTypesetterRef typeSetterRef = CTTypesetterCreateWithAttributedString((CFAttributedStringRef) attribString);
 
     CFRange range = {0, length};
     CTLineRef lineRef = CTTypesetterCreateLine(typeSetterRef, range);
--- a/src/macosx/native/sun/awt/DnDUtilities.h	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/macosx/native/sun/awt/DnDUtilities.h	Wed Sep 26 22:22:51 2012 -0700
@@ -42,7 +42,6 @@
 + (jint)narrowJavaDropActions:(jint)actions;
 
 // Mouse and key modifiers mapping:
-+ (NSUInteger)mapJavaExtModifiersToNSKeyModifiers:(jint)modifiers;
 + (NSUInteger)mapJavaExtModifiersToNSMouseDownButtons:(jint)modifiers;
 + (NSUInteger)mapJavaExtModifiersToNSMouseUpButtons:(jint)modifiers;
 
@@ -50,9 +49,6 @@
 + (jint)extractJavaExtKeyModifiersFromJavaExtModifiers:(jint)modifiers;
 + (jint)extractJavaExtMouseModifiersFromJavaExtModifiers:(jint)modifiers;
 
-// Get the current keyboard modifier keys as java modifiers (for operationChanged)
-+ (jint)currentJavaExtKeyModifiers;
-
 // Getting the state of the current Drag
 + (NSDragOperation)nsDragOperationForModifiers:(NSUInteger)modifiers;
 + (jint) javaKeyModifiersForNSDragOperation:(NSDragOperation)dragOp;
--- a/src/macosx/native/sun/awt/DnDUtilities.m	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/macosx/native/sun/awt/DnDUtilities.m	Wed Sep 26 22:22:51 2012 -0700
@@ -161,28 +161,6 @@
 }
 
 // Mouse and key modifiers mapping:
-+ (NSUInteger)mapJavaExtModifiersToNSKeyModifiers:(jint)modifiers
-{
-    NSUInteger result = 0;
-
-    if ((modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK) != 0)
-        result |= NSShiftKeyMask;
-
-    if ((modifiers & java_awt_event_InputEvent_CTRL_DOWN_MASK) != 0)
-        result |= NSControlKeyMask;
-
-    if ((modifiers & java_awt_event_InputEvent_META_DOWN_MASK) != 0)
-        result |= NSCommandKeyMask;
-
-    if ((modifiers & java_awt_event_InputEvent_ALT_DOWN_MASK) != 0)
-        result |= NSAlternateKeyMask;
-
-    if ((modifiers & java_awt_event_InputEvent_ALT_GRAPH_DOWN_MASK) != 0)
-        result |= NSAlternateKeyMask;
-
-    return result;
-}
-
 + (NSUInteger)mapJavaExtModifiersToNSMouseDownButtons:(jint)modifiers
 {
     NSUInteger result = NSLeftMouseDown;
@@ -245,32 +223,6 @@
     return modifiers & mask;
 }
 
-
-+ (jint)currentJavaExtKeyModifiers
-{
-    NSUInteger modifiers = [NSEvent modifierFlags];
-    jint jmodifiers = 0;
-
-    if(modifiers & NSShiftKeyMask) {
-        jmodifiers |= java_awt_event_InputEvent_SHIFT_DOWN_MASK;
-    }
-
-    if(modifiers & NSControlKeyMask) {
-        jmodifiers |= java_awt_event_InputEvent_CTRL_DOWN_MASK;
-    }
-
-    if(modifiers & NSAlternateKeyMask) {
-        jmodifiers |= java_awt_event_InputEvent_ALT_DOWN_MASK;
-    }
-
-    if(modifiers & NSCommandKeyMask) {
-        jmodifiers |= java_awt_event_InputEvent_META_DOWN_MASK;
-    }
-
-    return jmodifiers;
-}
-
-
 + (NSDragOperation) nsDragOperationForModifiers:(NSUInteger)modifiers {
 
     // Java first
--- a/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -644,6 +644,9 @@
                    "released SPACE", "released"
                  }),
 
+            "Caret.width",
+                  new DesktopProperty("win.caret.width", null),
+
             "CheckBox.font", ControlFont,
             "CheckBox.interiorBackground", WindowBackgroundColor,
             "CheckBox.background", ControlBackgroundColor,
--- a/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java	Wed Sep 26 22:22:51 2012 -0700
@@ -883,7 +883,7 @@
             avHiBits &= (1L<<attrIndexLimit[i])-1;
             int nextLoBit = 0;
             Map<Attribute.Layout, int[]> defMap = allLayouts.get(i);
-            @SuppressWarnings({ "unchecked", "rawtypes" })
+            @SuppressWarnings({"unchecked", "rawtypes"})
             Map.Entry<Attribute.Layout, int[]>[] layoutsAndCounts =
                     new Map.Entry[defMap.size()];
             defMap.entrySet().toArray(layoutsAndCounts);
--- a/src/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java	Wed Sep 26 22:22:51 2012 -0700
@@ -32,14 +32,15 @@
 
 import com.sun.jmx.remote.util.EnvHelp;
 
-import java.beans.ConstructorProperties;
 import java.io.InvalidObjectException;
+import java.lang.annotation.Annotation;
 import java.lang.annotation.ElementType;
 import java.lang.ref.WeakReference;
 import java.lang.reflect.Array;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
 import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.lang.reflect.ParameterizedType;
@@ -1129,14 +1130,56 @@
         to getters.  */
     private static final class CompositeBuilderViaConstructor
             extends CompositeBuilder {
+        static class AnnotationHelper {
+            private static Class<? extends Annotation> constructorPropertiesClass;
+            private static Method valueMethod;
+            static {
+                findConstructorPropertiesClass();
+            }
+
+            @SuppressWarnings("unchecked")
+            private static void findConstructorPropertiesClass() {
+                try {
+                    constructorPropertiesClass = (Class<? extends Annotation>)
+                        Class.forName("java.beans.ConstructorProperties", false,
+                                      DefaultMXBeanMappingFactory.class.getClassLoader());
+                    valueMethod = constructorPropertiesClass.getMethod("value");
+                } catch (ClassNotFoundException cnf) {
+                    // java.beans not present
+                } catch (NoSuchMethodException e) {
+                    // should not reach here
+                    throw new InternalError(e);
+                }
+            }
+
+            static boolean isAvailable() {
+                return constructorPropertiesClass != null;
+            }
+
+            static String[] getPropertyNames(Constructor<?> constr) {
+                if (!isAvailable())
+                    return null;
+
+                Annotation a = constr.getAnnotation(constructorPropertiesClass);
+                if (a == null) return null;
+
+                try {
+                    return (String[]) valueMethod.invoke(a);
+                } catch (InvocationTargetException e) {
+                    throw new InternalError(e);
+                } catch (IllegalAccessException e) {
+                    throw new InternalError(e);
+                }
+            }
+        }
 
         CompositeBuilderViaConstructor(Class<?> targetClass, String[] itemNames) {
             super(targetClass, itemNames);
         }
 
         String applicable(Method[] getters) throws InvalidObjectException {
-
-            final Class<ConstructorProperties> propertyNamesClass = ConstructorProperties.class;
+            if (!AnnotationHelper.isAvailable())
+                return "@ConstructorProperties annotation not available";
 
             Class<?> targetClass = getTargetClass();
             Constructor<?>[] constrs = targetClass.getConstructors();
@@ -1145,7 +1188,7 @@
             List<Constructor<?>> annotatedConstrList = newList();
             for (Constructor<?> constr : constrs) {
                 if (Modifier.isPublic(constr.getModifiers())
-                        && constr.getAnnotation(propertyNamesClass) != null)
+                        && AnnotationHelper.getPropertyNames(constr) != null)
                     annotatedConstrList.add(constr);
             }
 
@@ -1174,8 +1217,7 @@
             // so we can test unambiguity.
             Set<BitSet> getterIndexSets = newSet();
             for (Constructor<?> constr : annotatedConstrList) {
-                String[] propertyNames =
-                    constr.getAnnotation(propertyNamesClass).value();
+                String[] propertyNames = AnnotationHelper.getPropertyNames(constr);
 
                 Type[] paramTypes = constr.getGenericParameterTypes();
                 if (paramTypes.length != propertyNames.length) {
--- a/src/share/classes/com/sun/management/VMOption.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/com/sun/management/VMOption.java	Wed Sep 26 22:22:51 2012 -0700
@@ -178,7 +178,7 @@
         return "VM option: " + getName() +
                " value: " + value + " " +
                " origin: " + origin + " " +
-               (writeable ? "(read-only)" : "(read-write)");
+               (writeable ? "(read-write)" : "(read-only)");
     }
 
     /**
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/Init.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/Init.java	Wed Sep 26 22:22:51 2012 -0700
@@ -153,8 +153,8 @@
                         break;
                 }
             }
-                        for (Node el=config.getFirstChild();el!=null;el=el.getNextSibling()) {
-                if (!(el instanceof Element)) {
+            for (Node el=config.getFirstChild();el!=null;el=el.getNextSibling()) {
+                if (el.getNodeType() != Node.ELEMENT_NODE) {
                         continue;
                 }
                 String tag=el.getLocalName();
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java	Wed Sep 26 22:22:51 2012 -0700
@@ -205,7 +205,7 @@
         try {
          NameSpaceSymbTable ns=new NameSpaceSymbTable();
          int nodeLevel=NODE_BEFORE_DOCUMENT_ELEMENT;
-         if (rootNode instanceof Element) {
+         if (rootNode != null && rootNode.getNodeType() == Node.ELEMENT_NODE) {
                 //Fills the nssymbtable with the definitions of the parent of the root subnode
                 getParentNameSpaces((Element)rootNode,ns);
                 nodeLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
@@ -335,7 +335,7 @@
                                 return;
                         sibling=parentNode.getNextSibling();
                         parentNode=parentNode.getParentNode();
-                        if (!(parentNode instanceof Element)) {
+                        if (parentNode !=null && parentNode.getNodeType() != Node.ELEMENT_NODE) {
                                 documentLevel=NODE_AFTER_DOCUMENT_ELEMENT;
                                 parentNode=null;
                         }
@@ -391,7 +391,7 @@
                 return;
         boolean currentNodeIsVisible = false;
         NameSpaceSymbTable ns=new  NameSpaceSymbTable();
-        if (currentNode instanceof Element)
+        if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE)
                 getParentNameSpaces((Element)currentNode,ns);
         Node sibling=null;
         Node parentNode=null;
@@ -512,7 +512,7 @@
                                 return;
                         sibling=parentNode.getNextSibling();
                         parentNode=parentNode.getParentNode();
-                        if (!(parentNode instanceof Element)) {
+                        if (parentNode != null && parentNode.getNodeType() != Node.ELEMENT_NODE) {
                                 parentNode=null;
                                 documentLevel=NODE_AFTER_DOCUMENT_ELEMENT;
                         }
@@ -594,18 +594,14 @@
         final void getParentNameSpaces(Element el,NameSpaceSymbTable ns)  {
                 List<Element> parents=new ArrayList<Element>(10);
                 Node n1=el.getParentNode();
-                if (!(n1 instanceof Element)) {
+                if (n1 == null || n1.getNodeType() != Node.ELEMENT_NODE) {
                         return;
                 }
                 //Obtain all the parents of the elemnt
-                Element parent=(Element) n1;
-                while (parent!=null) {
-                        parents.add(parent);
-                        Node n=parent.getParentNode();
-                        if (!(n instanceof Element )) {
-                                break;
-                        }
-                        parent=(Element)n;
+                Node parent = n1;
+                while (parent!=null && parent.getNodeType() == Node.ELEMENT_NODE) {
+                        parents.add((Element)parent);
+                        parent = parent.getParentNode();
                 }
                 //Visit them in reverse order.
                 ListIterator<Element> it=parents.listIterator(parents.size());
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1445,7 +1445,7 @@
                 // The de-serialiser returns a fragment whose children we need to
                 // take on.
 
-                if (sourceParent instanceof Document) {
+                if (sourceParent != null && sourceParent.getNodeType() == Node.DOCUMENT_NODE) {
 
                     // If this is a content decryption, this may have problems
 
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java	Wed Sep 26 22:22:51 2012 -0700
@@ -283,7 +283,7 @@
            Element e=null;
            while (it.hasNext()) {
                    Node currentNode=it.next();
-                   if (currentNode instanceof Element) {
+                   if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE) {
                            e=(Element)currentNode;
                            break;
                    }
@@ -292,14 +292,14 @@
            List<Element> parents=new ArrayList<Element>(10);
 
                 //Obtain all the parents of the elemnt
-                do {
+                while (e != null) {
                         parents.add(e);
                         Node n=e.getParentNode();
-                        if (!(n instanceof Element )) {
+                        if (n == null || n.getNodeType() != Node.ELEMENT_NODE) {
                                 break;
                         }
                         e=(Element)n;
-                } while (e!=null);
+                }
                 //Visit them in reverse order.
                 ListIterator<Element> it2=parents.listIterator(parents.size()-1);
                 Element ele=null;
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java	Wed Sep 26 22:22:51 2012 -0700
@@ -225,7 +225,7 @@
         } while (sibling==null  && parentNode!=null) {
                         sibling=parentNode.getNextSibling();
                         parentNode=parentNode.getParentNode();
-                        if (!(parentNode instanceof Element)) {
+                        if (parentNode != null && parentNode.getNodeType() != Node.ELEMENT_NODE) {
                                 parentNode=null;
                         }
                 }
--- a/src/share/classes/com/sun/rowset/JdbcRowSetImpl.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/com/sun/rowset/JdbcRowSetImpl.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,7 +31,6 @@
 import java.io.*;
 import java.math.*;
 import java.util.*;
-import java.beans.*;
 
 import javax.sql.rowset.*;
 
@@ -83,12 +82,6 @@
      */
     private ResultSetMetaData resMD;
 
-    /**
-     * The property that helps to fire the property changed event when certain
-     * properties are changed in the <code>JdbcRowSet</code> object. This property
-     * is being added to satisfy Rave requirements.
-     */
-    private PropertyChangeSupport propertyChangeSupport;
 
     /**
      * The Vector holding the Match Columns
@@ -145,7 +138,6 @@
             throw new RuntimeException(ioe);
         }
 
-        propertyChangeSupport = new PropertyChangeSupport(this);
 
         initParams();
 
@@ -268,7 +260,6 @@
             throw new RuntimeException(ioe);
         }
 
-        propertyChangeSupport = new PropertyChangeSupport(this);
 
         initParams();
         // set the defaults
@@ -343,7 +334,6 @@
             throw new RuntimeException(ioe);
         }
 
-        propertyChangeSupport = new PropertyChangeSupport(this);
 
         initParams();
 
@@ -360,10 +350,6 @@
         setMaxRows(0);
         setMaxFieldSize(0);
 
-        // to ensure connection to a db call connect now
-        // and associate a conn with "this" object
-        // in this case.
-        conn = connect();
         setParams();
 
         setReadOnly(true);
@@ -435,7 +421,6 @@
             throw new RuntimeException(ioe);
         }
 
-        propertyChangeSupport = new PropertyChangeSupport(this);
 
         initParams();
 
@@ -620,12 +605,7 @@
 
     }
 
-    // An alternate solution is required instead of having the
-    // connect method as protected.
-    // This is a work around to assist Rave Team
-    // :ah
-
-    protected Connection connect() throws SQLException {
+    private Connection connect() throws SQLException {
 
         // Get a JDBC connection.
 
@@ -4056,9 +4036,7 @@
       // Added as per Rave requirements
 
       if( conn.getHoldability() != HOLD_CURSORS_OVER_COMMIT) {
-         ResultSet oldVal = rs;
          rs = null;
-         // propertyChangeSupport.firePropertyChange("ResultSet",oldVal,rs);
       }
     }
 
@@ -4119,9 +4097,7 @@
         // Makes the result ste handle null after rollback
         // Added as per Rave requirements
 
-        ResultSet oldVal = rs;
         rs = null;
-        // propertyChangeSupport.firePropertyChange("ResultSet", oldVal,rs);
     }
 
 
@@ -4247,12 +4223,6 @@
        rs = resultSet;
     }
 
-
-    // Over riding the setCommand from BaseRowSet for
-    // firing the propertyChangeSupport Event for
-    // Rave requirements when this property's value
-    // changes.
-
     /**
      * Sets this <code>JdbcRowSet</code> object's <code>command</code> property to
      * the given <code>String</code> object and clears the parameters, if any,
@@ -4277,28 +4247,19 @@
      * @see #getCommand
      */
     public void setCommand(String command) throws SQLException {
-       String oldVal;
 
        if (getCommand() != null) {
           if(!getCommand().equals(command)) {
-             oldVal = getCommand();
              super.setCommand(command);
              ps = null;
              rs = null;
-             propertyChangeSupport.firePropertyChange("command", oldVal,command);
           }
        }
        else {
           super.setCommand(command);
-          propertyChangeSupport.firePropertyChange("command", null,command);
        }
     }
 
-    // Over riding the setDataSourceName from BaseRowSet for
-    // firing the propertyChangeSupport Event for
-    // Rave requirements when this property's values
-    // changes.
-
     /**
      * Sets the <code>dataSourceName</code> property for this <code>JdbcRowSet</code>
      * object to the given logical name and sets this <code>JdbcRowSet</code> object's
@@ -4329,28 +4290,20 @@
      * @see #getDataSourceName
      */
     public void setDataSourceName(String dsName) throws SQLException{
-       String oldVal;
 
        if(getDataSourceName() != null) {
           if(!getDataSourceName().equals(dsName)) {
-             oldVal = getDataSourceName();
              super.setDataSourceName(dsName);
              conn = null;
              ps = null;
              rs = null;
-             propertyChangeSupport.firePropertyChange("dataSourceName",oldVal,dsName);
           }
        }
        else {
           super.setDataSourceName(dsName);
-          propertyChangeSupport.firePropertyChange("dataSourceName",null,dsName);
        }
     }
 
-    // Over riding the setUrl from BaseRowSet for
-    // firing the propertyChangeSupport Event for
-    // Rave requirements when this property's values
-    // changes.
 
     /**
      * Sets the Url property for this <code>JdbcRowSet</code> object
@@ -4394,29 +4347,20 @@
      */
 
     public void setUrl(String url) throws SQLException {
-       String oldVal;
 
        if(getUrl() != null) {
           if(!getUrl().equals(url)) {
-             oldVal = getUrl();
              super.setUrl(url);
              conn = null;
              ps = null;
              rs = null;
-             propertyChangeSupport.firePropertyChange("url", oldVal, url);
           }
        }
        else {
           super.setUrl(url);
-          propertyChangeSupport.firePropertyChange("url", null, url);
        }
     }
 
-    // Over riding the setUsername from BaseRowSet for
-    // firing the propertyChangeSupport Event for
-    // Rave requirements when this property's values
-    // changes.
-
      /**
      * Sets the username property for this <code>JdbcRowSet</code> object
      * to the given user name. Because it
@@ -4438,29 +4382,20 @@
      * @see #getUsername
      */
     public void setUsername(String uname) {
-       String oldVal;
 
        if( getUsername() != null) {
           if(!getUsername().equals(uname)) {
-             oldVal = getUsername();
              super.setUsername(uname);
              conn = null;
              ps = null;
              rs = null;
-             propertyChangeSupport.firePropertyChange("username",oldVal,uname);
           }
        }
        else{
           super.setUsername(uname);
-          propertyChangeSupport.firePropertyChange("username",null,uname);
        }
     }
 
-    // Over riding the setPassword from BaseRowSet for
-    // firing the propertyChangeSupport Event for
-    // Rave requirements when this property's values
-    // changes.
-
      /**
      * Sets the password property for this <code>JdbcRowSet</code> object
      * to the given <code>String</code> object. Because it
@@ -4481,21 +4416,17 @@
      *     that must be supplied to the database to create a connection
      */
     public void setPassword(String password) {
-       String oldVal;
 
        if ( getPassword() != null) {
           if(!getPassword().equals(password)) {
-             oldVal = getPassword();
              super.setPassword(password);
              conn = null;
              ps = null;
              rs = null;
-             propertyChangeSupport.firePropertyChange("password",oldVal,password);
           }
        }
        else{
           super.setPassword(password);
-          propertyChangeSupport.firePropertyChange("password",null,password);
        }
     }
 
@@ -4528,7 +4459,6 @@
 
        if(oldVal != type) {
            super.setType(type);
-           propertyChangeSupport.firePropertyChange("type",oldVal,type);
        }
 
     }
@@ -4561,78 +4491,6 @@
 
        if(oldVal != concur) {
            super.setConcurrency(concur);
-           propertyChangeSupport.firePropertyChange("concurrency",oldVal,concur);
-       }
-
-    }
-
-    /**
-     * Sets the transaction isolation property for this JDBC <code>RowSet</code> object to the given
-     * constant. The DBMS will use this transaction isolation level for
-     * transactions if it can.
-     * <p>
-     * For <code>RowSet</code> implementations such as
-     * the <code>CachedRowSet</code> that operate in a disconnected environment,
-     * the <code>SyncProvider</code> object being used
-     * offers complementary locking and data integrity options. The
-     * options described below are pertinent only to connected <code>RowSet</code>
-     * objects (<code>JdbcRowSet</code> objects).
-     *
-     * @param transIso one of the following constants, listed in ascending order:
-     *              <code>Connection.TRANSACTION_NONE</code>,
-     *              <code>Connection.TRANSACTION_READ_UNCOMMITTED</code>,
-     *              <code>Connection.TRANSACTION_READ_COMMITTED</code>,
-     *              <code>Connection.TRANSACTION_REPEATABLE_READ</code>, or
-     *              <code>Connection.TRANSACTION_SERIALIZABLE</code>
-     * @throws SQLException if the given parameter is not one of the Connection
-     *          constants
-     * @see javax.sql.rowset.spi.SyncFactory
-     * @see javax.sql.rowset.spi.SyncProvider
-     * @see #getTransactionIsolation
-     */
-    public void setTransactionIsolation(int transIso) throws SQLException {
-
-       int oldVal;
-
-       try {
-          oldVal = getTransactionIsolation();
-        }catch(NullPointerException ex) {
-           oldVal = 0;
-        }
-
-       if(oldVal != transIso) {
-           super.setTransactionIsolation(transIso);
-           propertyChangeSupport.firePropertyChange("transactionIsolation",oldVal,transIso);
-       }
-
-    }
-
-    /**
-     * Sets the maximum number of rows that this <code>RowSet</code> object may contain to
-     * the given number. If this limit is exceeded, the excess rows are
-     * silently dropped.
-     *
-     * @param mRows an <code>int</code> indicating the current maximum number
-     *     of rows; zero means that there is no limit
-     * @throws SQLException if an error occurs internally setting the
-     *     maximum limit on the number of rows that a JDBC <code>RowSet</code> object
-     *     can contain; or if <i>max</i> is less than <code>0</code>; or
-     *     if <i>max</i> is less than the <code>fetchSize</code> of the
-     *     <code>RowSet</code>
-     */
-    public void setMaxRows(int mRows) throws SQLException {
-
-       int oldVal;
-
-       try {
-          oldVal = getMaxRows();
-        }catch(NullPointerException ex) {
-           oldVal = 0;
-        }
-
-       if(oldVal != mRows) {
-           super.setMaxRows(mRows);
-           propertyChangeSupport.firePropertyChange("maxRows",oldVal,mRows);
        }
 
     }
--- a/src/share/classes/com/sun/security/auth/callback/DialogCallbackHandler.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/com/sun/security/auth/callback/DialogCallbackHandler.java	Wed Sep 26 22:22:51 2012 -0700
@@ -52,7 +52,9 @@
  * This can be used by a JAAS application to instantiate a
  * CallbackHandler
  * @see javax.security.auth.callback
+ * @deprecated This class will be removed in a future release.
  */
+@Deprecated
 public class DialogCallbackHandler implements CallbackHandler {
 
     /* -- Fields -- */
--- a/src/share/classes/java/awt/EventQueue.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/awt/EventQueue.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1047,6 +1047,10 @@
 
     final boolean detachDispatchThread(EventDispatchThread edt, boolean forceDetach) {
         /*
+         * Minimize discard possibility for non-posted events
+         */
+        SunToolkit.flushPendingEvents();
+        /*
          * This synchronized block is to secure that the event dispatch
          * thread won't die in the middle of posting a new event to the
          * associated event queue. It is important because we notify
@@ -1060,11 +1064,8 @@
                 /*
                  * Don't detach the thread if any events are pending. Not
                  * sure if it's a possible scenario, though.
-                 *
-                 * Fix for 4648733. Check both the associated java event
-                 * queue and the PostEventQueue.
                  */
-                if (!forceDetach && (peekEvent() != null) || !SunToolkit.isPostEventQueueEmpty()) {
+                if (!forceDetach && (peekEvent() != null)) {
                     return false;
                 }
                 dispatchThread = null;
--- a/src/share/classes/java/beans/IndexedPropertyDescriptor.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/beans/IndexedPropertyDescriptor.java	Wed Sep 26 22:22:51 2012 -0700
@@ -495,6 +495,16 @@
         indexedReadMethodName = old.indexedReadMethodName;
     }
 
+    void updateGenericsFor(Class<?> type) {
+        super.updateGenericsFor(type);
+        try {
+            setIndexedPropertyType(findIndexedPropertyType(getIndexedReadMethod0(), getIndexedWriteMethod0()));
+        }
+        catch (IntrospectionException exception) {
+            setIndexedPropertyType(null);
+        }
+    }
+
     /**
      * Returns a hash code value for the object.
      * See {@link java.lang.Object#hashCode} for a complete description.
--- a/src/share/classes/java/beans/Introspector.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/beans/Introspector.java	Wed Sep 26 22:22:51 2012 -0700
@@ -574,26 +574,25 @@
             // replace existing property descriptor
             // only if we have types to resolve
             // in the context of this.beanClass
-            try {
-                String name = pd.getName();
-                Method read = pd.getReadMethod();
-                Method write = pd.getWriteMethod();
-                boolean cls = true;
-                if (read != null) cls = cls && read.getGenericReturnType() instanceof Class;
-                if (write != null) cls = cls && write.getGenericParameterTypes()[0] instanceof Class;
-                if (pd instanceof IndexedPropertyDescriptor) {
-                    IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor)pd;
-                    Method readI = ipd.getIndexedReadMethod();
-                    Method writeI = ipd.getIndexedWriteMethod();
-                    if (readI != null) cls = cls && readI.getGenericReturnType() instanceof Class;
-                    if (writeI != null) cls = cls && writeI.getGenericParameterTypes()[1] instanceof Class;
-                    if (!cls) {
-                        pd = new IndexedPropertyDescriptor(this.beanClass, name, read, write, readI, writeI);
-                    }
-                } else if (!cls) {
-                    pd = new PropertyDescriptor(this.beanClass, name, read, write);
+            Method read = pd.getReadMethod();
+            Method write = pd.getWriteMethod();
+            boolean cls = true;
+            if (read != null) cls = cls && read.getGenericReturnType() instanceof Class;
+            if (write != null) cls = cls && write.getGenericParameterTypes()[0] instanceof Class;
+            if (pd instanceof IndexedPropertyDescriptor) {
+                IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
+                Method readI = ipd.getIndexedReadMethod();
+                Method writeI = ipd.getIndexedWriteMethod();
+                if (readI != null) cls = cls && readI.getGenericReturnType() instanceof Class;
+                if (writeI != null) cls = cls && writeI.getGenericParameterTypes()[1] instanceof Class;
+                if (!cls) {
+                    pd = new IndexedPropertyDescriptor(ipd);
+                    pd.updateGenericsFor(this.beanClass);
                 }
-            } catch ( IntrospectionException e ) {
+            }
+            else if (!cls) {
+                pd = new PropertyDescriptor(pd);
+                pd.updateGenericsFor(this.beanClass);
             }
         }
         list.add(pd);
--- a/src/share/classes/java/beans/PropertyDescriptor.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/beans/PropertyDescriptor.java	Wed Sep 26 22:22:51 2012 -0700
@@ -632,6 +632,16 @@
         constrained = old.constrained;
     }
 
+    void updateGenericsFor(Class<?> type) {
+        setClass0(type);
+        try {
+            setPropertyType(findPropertyType(getReadMethod0(), getWriteMethod0()));
+        }
+        catch (IntrospectionException exception) {
+            setPropertyType(null);
+        }
+    }
+
     /**
      * Returns the property type that corresponds to the read and write method.
      * The type precedence is given to the readMethod.
--- a/src/share/classes/java/io/FilePermission.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/io/FilePermission.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,10 +31,6 @@
 import java.util.ArrayList;
 import java.util.Vector;
 import java.util.Collections;
-import java.io.ObjectStreamField;
-import java.io.ObjectOutputStream;
-import java.io.ObjectInputStream;
-import java.io.IOException;
 import sun.security.util.SecurityConstants;
 
 /**
@@ -424,7 +420,7 @@
     /**
      * Converts an actions String to an actions mask.
      *
-     * @param action the action string.
+     * @param actions the action string.
      * @return the actions mask.
      */
     private static int getMask(String actions) {
@@ -435,7 +431,9 @@
         if (actions == null) {
             return mask;
         }
-        // Check against use of constants (used heavily within the JDK)
+
+        // Use object identity comparison against known-interned strings for
+        // performance benefit (these values are used heavily within the JDK).
         if (actions == SecurityConstants.FILE_READ_ACTION) {
             return READ;
         } else if (actions == SecurityConstants.FILE_WRITE_ACTION) {
@@ -531,7 +529,7 @@
                 switch(a[i-matchlen]) {
                 case ',':
                     seencomma = true;
-                    /*FALLTHROUGH*/
+                    break;
                 case ' ': case '\r': case '\n':
                 case '\f': case '\t':
                     break;
@@ -798,7 +796,7 @@
      * @return an enumeration of all the FilePermission objects.
      */
 
-    public Enumeration elements() {
+    public Enumeration<Permission> elements() {
         // Convert Iterator into Enumeration
         synchronized (this) {
             return Collections.enumeration(perms);
@@ -843,7 +841,6 @@
     /*
      * Reads in a Vector of FilePermissions and saves them in the perms field.
      */
-    @SuppressWarnings("unchecked")
     private void readObject(ObjectInputStream in) throws IOException,
     ClassNotFoundException {
         // Don't call defaultReadObject()
@@ -852,6 +849,7 @@
         ObjectInputStream.GetField gfields = in.readFields();
 
         // Get the one we want
+        @SuppressWarnings("unchecked")
         Vector<Permission> permissions = (Vector<Permission>)gfields.get("permissions", null);
         perms = new ArrayList<>(permissions.size());
         perms.addAll(permissions);
--- a/src/share/classes/java/lang/AbstractStringBuilder.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/lang/AbstractStringBuilder.java	Wed Sep 26 22:22:51 2012 -0700
@@ -96,6 +96,8 @@
      * </ul>
      * If the {@code minimumCapacity} argument is nonpositive, this
      * method takes no action and simply returns.
+     * Note that subsequent operations on this object can reduce the
+     * actual capacity below that requested here.
      *
      * @param   minimumCapacity   the minimum desired capacity.
      */
--- a/src/share/classes/java/lang/management/LockInfo.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/lang/management/LockInfo.java	Wed Sep 26 22:22:51 2012 -0700
@@ -27,7 +27,7 @@
 
 import javax.management.openmbean.CompositeData;
 import java.util.concurrent.locks.*;
-import java.beans.ConstructorProperties;
+import sun.management.LockInfoCompositeData;
 
 /**
  * Information about a <em>lock</em>.  A lock can be a built-in object monitor,
@@ -44,8 +44,7 @@
  *
  * <h4><a name="MappedType">MXBean Mapping</a></h4>
  * <tt>LockInfo</tt> is mapped to a {@link CompositeData CompositeData}
- * as specified in the <a href="../../../javax/management/MXBean.html#mapping-rules">
- * type mapping rules</a> of {@linkplain javax.management.MXBean MXBeans}.
+ * as specified in the {@link #from from} method.
  *
  * @see java.util.concurrent.locks.AbstractOwnableSynchronizer
  * @see java.util.concurrent.locks.Condition
@@ -66,7 +65,6 @@
      * @param identityHashCode the {@link System#identityHashCode
      *                         identity hash code} of the lock object.
      */
-    @ConstructorProperties({"className", "identityHashCode"})
     public LockInfo(String className, int identityHashCode) {
         if (className == null) {
             throw new NullPointerException("Parameter className cannot be null");
@@ -103,6 +101,50 @@
     }
 
     /**
+     * Returns a {@code LockInfo} object represented by the
+     * given {@code CompositeData}.
+     * The given {@code CompositeData} must contain the following attributes:
+     * <blockquote>
+     * <table border>
+     * <tr>
+     *   <th align=left>Attribute Name</th>
+     *   <th align=left>Type</th>
+     * </tr>
+     * <tr>
+     *   <td>className</td>
+     *   <td><tt>java.lang.String</tt></td>
+     * </tr>
+     * <tr>
+     *   <td>identityHashCode</td>
+     *   <td><tt>java.lang.Integer</tt></td>
+     * </tr>
+     * </table>
+     * </blockquote>
+     *
+     * @param cd {@code CompositeData} representing a {@code LockInfo}
+     *
+     * @throws IllegalArgumentException if {@code cd} does not
+     *   represent a {@code LockInfo} with the attributes described
+     *   above.
+     * @return a {@code LockInfo} object represented
+     *         by {@code cd} if {@code cd} is not {@code null};
+     *         {@code null} otherwise.
+     *
+     * @since 1.8
+     */
+    public static LockInfo from(CompositeData cd) {
+        if (cd == null) {
+            return null;
+        }
+
+        if (cd instanceof LockInfoCompositeData) {
+            return ((LockInfoCompositeData) cd).getLockInfo();
+        } else {
+            return LockInfoCompositeData.toLockInfo(cd);
+        }
+    }
+
+    /**
      * Returns a string representation of a lock.  The returned
      * string representation consists of the name of the class of the
      * lock object, the at-sign character `@', and the unsigned
--- a/src/share/classes/java/lang/management/ThreadInfo.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/lang/management/ThreadInfo.java	Wed Sep 26 22:22:51 2012 -0700
@@ -696,9 +696,7 @@
      *   <td>lockInfo</td>
      *   <td><tt>javax.management.openmbean.CompositeData</tt>
      *       - the mapped type for {@link LockInfo} as specified in the
-     *       <a href="../../../javax/management/MXBean.html#mapping-rules">
-     *       type mapping rules</a> of
-     *       {@linkplain javax.management.MXBean MXBeans}.
+     *         {@link LockInfo#from} method.
      *       <p>
      *       If <tt>cd</tt> does not contain this attribute,
      *       the <tt>LockInfo</tt> object will be constructed from
@@ -766,10 +764,7 @@
      *   <td>lockedSynchronizers</td>
      *   <td><tt>javax.management.openmbean.CompositeData[]</tt>
      *       whose element type is the mapped type for
-     *       {@link LockInfo} as specified in the
-     *       <a href="../../../javax/management/MXBean.html#mapping-rules">
-     *       type mapping rules</a> of
-     *       {@linkplain javax.management.MXBean MXBeans}.
+     *       {@link LockInfo} as specified in the {@link LockInfo#from} method.
      *       <p>
      *       If <tt>cd</tt> does not contain this attribute,
      *       this attribute will be set to an empty array. </td>
@@ -830,7 +825,6 @@
      * @since 1.6
      */
     public LockInfo[] getLockedSynchronizers() {
-       // represents an <a href="LockInfo.html#OwnableSynchronizer">
         return lockedSynchronizers;
     }
 
--- a/src/share/classes/java/lang/reflect/Constructor.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/lang/reflect/Constructor.java	Wed Sep 26 22:22:51 2012 -0700
@@ -182,7 +182,7 @@
      * @since 1.5
      */
     @Override
-    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @SuppressWarnings({"rawtypes", "unchecked"})
     public TypeVariable<Constructor<T>>[] getTypeParameters() {
       if (getSignature() != null) {
         return (TypeVariable<Constructor<T>>[])getGenericInfo().getTypeParameters();
--- a/src/share/classes/java/lang/reflect/Method.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/lang/reflect/Method.java	Wed Sep 26 22:22:51 2012 -0700
@@ -194,7 +194,7 @@
      * @since 1.5
      */
     @Override
-    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @SuppressWarnings({"rawtypes", "unchecked"})
     public TypeVariable<Method>[] getTypeParameters() {
         if (getGenericSignature() != null)
             return (TypeVariable<Method>[])getGenericInfo().getTypeParameters();
--- a/src/share/classes/java/net/SocketPermission.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/net/SocketPermission.java	Wed Sep 26 22:22:51 2012 -0700
@@ -467,7 +467,6 @@
      * @param action the action string
      * @return the action mask
      */
-    @SuppressWarnings("fallthrough")
     private static int getMask(String action) {
 
         if (action == null) {
@@ -480,7 +479,8 @@
 
         int mask = NONE;
 
-        // Check against use of constants (used heavily within the JDK)
+        // Use object identity comparison against known-interned strings for
+        // performance benefit (these values are used heavily within the JDK).
         if (action == SecurityConstants.SOCKET_RESOLVE_ACTION) {
             return RESOLVE;
         } else if (action == SecurityConstants.SOCKET_CONNECT_ACTION) {
@@ -568,7 +568,7 @@
                 switch(a[i-matchlen]) {
                 case ',':
                     seencomma = true;
-                    /*FALLTHROUGH*/
+                    break;
                 case ' ': case '\r': case '\n':
                 case '\f': case '\t':
                     break;
--- a/src/share/classes/java/nio/channels/AsynchronousFileChannel.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/nio/channels/AsynchronousFileChannel.java	Wed Sep 26 22:22:51 2012 -0700
@@ -248,7 +248,7 @@
         return provider.newAsynchronousFileChannel(file, options, executor, attrs);
     }
 
-    @SuppressWarnings({ "unchecked", "rawtypes" }) // generic array construction
+    @SuppressWarnings({"unchecked", "rawtypes"}) // generic array construction
     private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0];
 
     /**
--- a/src/share/classes/java/nio/channels/FileChannel.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/nio/channels/FileChannel.java	Wed Sep 26 22:22:51 2012 -0700
@@ -287,7 +287,7 @@
         return provider.newFileChannel(path, options, attrs);
     }
 
-    @SuppressWarnings({ "unchecked", "rawtypes" }) // generic array construction
+    @SuppressWarnings({"unchecked", "rawtypes"}) // generic array construction
     private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0];
 
     /**
--- a/src/share/classes/java/util/ArrayDeque.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/ArrayDeque.java	Wed Sep 26 22:22:51 2012 -0700
@@ -121,6 +121,7 @@
      *
      * @param numElements  the number of elements to hold
      */
+    @SuppressWarnings("unchecked")
     private void allocateElements(int numElements) {
         int initialCapacity = MIN_INITIAL_CAPACITY;
         // Find the best power of two to hold elements.
@@ -152,10 +153,11 @@
         int newCapacity = n << 1;
         if (newCapacity < 0)
             throw new IllegalStateException("Sorry, deque too big");
-        Object[] a = new Object[newCapacity];
+        @SuppressWarnings("unchecked")
+        E[] a = (E[]) new Object[newCapacity];
         System.arraycopy(elements, p, a, 0, r);
         System.arraycopy(elements, 0, a, r, p);
-        elements = (E[])a;
+        elements = a;
         head = 0;
         tail = n;
     }
@@ -182,6 +184,7 @@
      * Constructs an empty array deque with an initial capacity
      * sufficient to hold 16 elements.
      */
+    @SuppressWarnings("unchecked")
     public ArrayDeque() {
         elements = (E[]) new Object[16];
     }
@@ -793,6 +796,7 @@
      *         this deque
      * @throws NullPointerException if the specified array is null
      */
+    @SuppressWarnings("unchecked")
     public <T> T[] toArray(T[] a) {
         int size = size();
         if (a.length < size)
--- a/src/share/classes/java/util/Arrays.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/Arrays.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -560,7 +560,7 @@
      * off is the offset to generate corresponding low, high in src
      * To be removed in a future release.
      */
-    @SuppressWarnings({ "unchecked", "rawtypes" })
+    @SuppressWarnings({"unchecked", "rawtypes"})
     private static void mergeSort(Object[] src,
                                   Object[] dest,
                                   int low,
@@ -747,7 +747,7 @@
      * off is the offset into src corresponding to low in dest
      * To be removed in a future release.
      */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @SuppressWarnings({"rawtypes", "unchecked"})
     private static void mergeSort(Object[] src,
                                   Object[] dest,
                                   int low, int high, int off,
@@ -2832,6 +2832,7 @@
      * @return a list view of the specified array
      */
     @SafeVarargs
+    @SuppressWarnings("varargs")
     public static <T> List<T> asList(T... a) {
         return new ArrayList<>(a);
     }
--- a/src/share/classes/java/util/Collections.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/Collections.java	Wed Sep 26 22:22:51 2012 -0700
@@ -213,7 +213,7 @@
      * @throws IllegalArgumentException (optional) if the comparator is
      *         found to violate the {@link Comparator} contract
      */
-    @SuppressWarnings({ "unchecked", "rawtypes" })
+    @SuppressWarnings({"unchecked", "rawtypes"})
     public static <T> void sort(List<T> list, Comparator<? super T> c) {
         Object[] a = list.toArray();
         Arrays.sort(a, (Comparator)c);
@@ -418,7 +418,7 @@
      * @throws UnsupportedOperationException if the specified list or
      *         its list-iterator does not support the <tt>set</tt> operation.
      */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @SuppressWarnings({"rawtypes", "unchecked"})
     public static void reverse(List<?> list) {
         int size = list.size();
         if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
@@ -497,7 +497,7 @@
      * @throws UnsupportedOperationException if the specified list or its
      *         list-iterator does not support the <tt>set</tt> operation.
      */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @SuppressWarnings({"rawtypes", "unchecked"})
     public static void shuffle(List<?> list, Random rnd) {
         int size = list.size();
         if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
@@ -535,7 +535,7 @@
      *         || j &lt; 0 || j &gt;= list.size()).
      * @since 1.4
      */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @SuppressWarnings({"rawtypes", "unchecked"})
     public static void swap(List<?> list, int i, int j) {
         // instead of using a raw type here, it's possible to capture
         // the wildcard but it will require a call to a supplementary
@@ -669,7 +669,7 @@
      * @throws NoSuchElementException if the collection is empty.
      * @see Comparable
      */
-    @SuppressWarnings({ "unchecked", "rawtypes" })
+    @SuppressWarnings({"unchecked", "rawtypes"})
     public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
         if (comp==null)
             return (T)min((Collection) coll);
@@ -740,7 +740,7 @@
      * @throws NoSuchElementException if the collection is empty.
      * @see Comparable
      */
-    @SuppressWarnings({ "unchecked", "rawtypes" })
+    @SuppressWarnings({"unchecked", "rawtypes"})
     public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
         if (comp==null)
             return (T)max((Collection) coll);
@@ -1403,7 +1403,7 @@
             extends UnmodifiableSet<Map.Entry<K,V>> {
             private static final long serialVersionUID = 7854390611657943733L;
 
-            @SuppressWarnings({ "unchecked", "rawtypes" })
+            @SuppressWarnings({"unchecked", "rawtypes"})
             UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
                 // Need to cast to raw in order to work around a limitation in the type system
                 super((Set)s);
@@ -3172,7 +3172,7 @@
      *
      * @see #emptySet()
      */
-    @SuppressWarnings("unchecked")
+    @SuppressWarnings("rawtypes")
     public static final Set EMPTY_SET = new EmptySet<>();
 
     /**
@@ -3271,10 +3271,13 @@
             return new EmptySortedSet<>();
         }
 
-        public Comparator comparator() {
+        @Override
+        public Comparator<? super E> comparator() {
             return null;
         }
 
+        @Override
+        @SuppressWarnings("unchecked")
         public SortedSet<E> subSet(Object fromElement, Object toElement) {
             Objects.requireNonNull(fromElement);
             Objects.requireNonNull(toElement);
@@ -3294,6 +3297,7 @@
             return emptySortedSet();
         }
 
+        @Override
         public SortedSet<E> headSet(Object toElement) {
             Objects.requireNonNull(toElement);
 
@@ -3304,6 +3308,7 @@
             return emptySortedSet();
         }
 
+        @Override
         public SortedSet<E> tailSet(Object fromElement) {
             Objects.requireNonNull(fromElement);
 
@@ -3314,10 +3319,12 @@
             return emptySortedSet();
         }
 
+        @Override
         public E first() {
             throw new NoSuchElementException();
         }
 
+        @Override
         public E last() {
             throw new NoSuchElementException();
         }
@@ -3328,7 +3335,7 @@
      *
      * @see #emptyList()
      */
-    @SuppressWarnings("unchecked")
+    @SuppressWarnings("rawtypes")
     public static final List EMPTY_LIST = new EmptyList<>();
 
     /**
@@ -3402,7 +3409,7 @@
      * @see #emptyMap()
      * @since 1.3
      */
-    @SuppressWarnings("unchecked")
+    @SuppressWarnings("rawtypes")
     public static final Map EMPTY_MAP = new EmptyMap<>();
 
     /**
@@ -3685,6 +3692,7 @@
             return a;
         }
 
+        @SuppressWarnings("unchecked")
         public <T> T[] toArray(T[] a) {
             final int n = this.n;
             if (a.length < n) {
@@ -3731,6 +3739,7 @@
      *         the <tt>Comparable</tt> interface.
      * @see Comparable
      */
+    @SuppressWarnings("unchecked")
     public static <T> Comparator<T> reverseOrder() {
         return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
     }
--- a/src/share/classes/java/util/ComparableTimSort.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/ComparableTimSort.java	Wed Sep 26 22:22:51 2012 -0700
@@ -208,7 +208,7 @@
      * @param start the index of the first element in the range that is
      *        not already known to be sorted ({@code lo <= start <= hi})
      */
-    @SuppressWarnings({ "fallthrough", "rawtypes", "unchecked" })
+    @SuppressWarnings({"fallthrough", "rawtypes", "unchecked"})
     private static void binarySort(Object[] a, int lo, int hi, int start) {
         assert lo <= start && start <= hi;
         if (start == lo)
@@ -277,7 +277,7 @@
      * @return  the length of the run beginning at the specified position in
      *          the specified array
      */
-    @SuppressWarnings({ "unchecked", "rawtypes" })
+    @SuppressWarnings({"unchecked", "rawtypes"})
     private static int countRunAndMakeAscending(Object[] a, int lo, int hi) {
         assert lo < hi;
         int runHi = lo + 1;
@@ -612,7 +612,7 @@
      *        (must be aBase + aLen)
      * @param len2  length of second run to be merged (must be > 0)
      */
-    @SuppressWarnings({ "unchecked", "rawtypes" })
+    @SuppressWarnings({"unchecked", "rawtypes"})
     private void mergeLo(int base1, int len1, int base2, int len2) {
         assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
 
@@ -729,7 +729,7 @@
      *        (must be aBase + aLen)
      * @param len2  length of second run to be merged (must be > 0)
      */
-    @SuppressWarnings({ "unchecked", "rawtypes" })
+    @SuppressWarnings({"unchecked", "rawtypes"})
     private void mergeHi(int base1, int len1, int base2, int len2) {
         assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
 
--- a/src/share/classes/java/util/Currency.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/Currency.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,6 +34,8 @@
 import java.io.Serializable;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 import java.util.regex.Pattern;
@@ -60,7 +62,14 @@
  * and the ISO 4217 currency data respectively.  The value part consists of
  * three ISO 4217 values of a currency, i.e., an alphabetic code, a numeric
  * code, and a minor unit.  Those three ISO 4217 values are separated by commas.
- * The lines which start with '#'s are considered comment lines.  For example,
+ * The lines which start with '#'s are considered comment lines. An optional UTC
+ * timestamp may be specified per currency entry if users need to specify a
+ * cutover date indicating when the new data comes into effect. The timestamp is
+ * appended to the end of the currency properties and uses a comma as a separator.
+ * If a UTC datestamp is present and valid, the JRE will only use the new currency
+ * properties if the current UTC date is later than the date specified at class
+ * loading time. The format of the timestamp must be of ISO 8601 format :
+ * {@code 'yyyy-MM-dd'T'HH:mm:ss'}. For example,
  * <p>
  * <code>
  * #Sample currency properties<br>
@@ -69,6 +78,20 @@
  * <p>
  * will supersede the currency data for Japan.
  *
+ * <p>
+ * <code>
+ * #Sample currency properties with cutover date<br>
+ * JP=JPZ,999,0,2014-01-01T00:00:00
+ * </code>
+ * <p>
+ * will supersede the currency data for Japan if {@code Currency} class is loaded after
+ * 1st January 2014 00:00:00 GMT.
+ * <p>
+ * Where syntactically malformed entries are encountered, the entry is ignored
+ * and the remainder of entries in file are processed. For instances where duplicate
+ * country code entries exist, the behavior of the Currency information for that
+ * {@code Currency} is undefined and the remainder of entries in file are processed.
+ *
  * @since 1.4
  */
 public final class Currency implements Serializable {
@@ -100,7 +123,6 @@
     private static ConcurrentMap<String, Currency> instances = new ConcurrentHashMap<>(7);
     private static HashSet<Currency> available;
 
-
     // Class data: currency data obtained from currency.data file.
     // Purpose:
     // - determine valid country codes
@@ -235,7 +257,9 @@
                         }
                         Set<String> keys = props.stringPropertyNames();
                         Pattern propertiesPattern =
-                            Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*([0-3])");
+                            Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*" +
+                                "([0-3])\\s*,?\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:" +
+                                "\\d{2}:\\d{2})?");
                         for (String key : keys) {
                            replaceCurrencyData(propertiesPattern,
                                key.toUpperCase(Locale.ROOT),
@@ -645,29 +669,38 @@
      *    consists of "three-letter alphabet code", "three-digit numeric code",
      *    and "one-digit (0,1,2, or 3) default fraction digit".
      *    For example, "JPZ,392,0".
-     * @throws
+     *    An optional UTC date can be appended to the string (comma separated)
+     *    to allow a currency change take effect after date specified.
+     *    For example, "JP=JPZ,999,0,2014-01-01T00:00:00" has no effect unless
+     *    UTC time is past 1st January 2014 00:00:00 GMT.
      */
     private static void replaceCurrencyData(Pattern pattern, String ctry, String curdata) {
 
         if (ctry.length() != 2) {
             // ignore invalid country code
-            String message = new StringBuilder()
-                .append("The entry in currency.properties for ")
-                .append(ctry).append(" is ignored because of the invalid country code.")
-                .toString();
-            info(message, null);
+            info("currency.properties entry for " + ctry +
+                    " is ignored because of the invalid country code.", null);
             return;
         }
 
         Matcher m = pattern.matcher(curdata);
-        if (!m.find()) {
+        if (!m.find() || (m.group(4) == null && countOccurrences(curdata, ',') >= 3)) {
             // format is not recognized.  ignore the data
-            String message = new StringBuilder()
-                .append("The entry in currency.properties for ")
-                .append(ctry)
-                .append(" is ignored because the value format is not recognized.")
-                .toString();
-            info(message, null);
+            // if group(4) date string is null and we've 4 values, bad date value
+            info("currency.properties entry for " + ctry +
+                    " ignored because the value format is not recognized.", null);
+            return;
+        }
+
+        try {
+            if (m.group(4) != null && !isPastCutoverDate(m.group(4))) {
+                info("currency.properties entry for " + ctry +
+                        " ignored since cutover date has not passed :" + curdata, null);
+                return;
+            }
+        } catch (IndexOutOfBoundsException | NullPointerException | ParseException ex) {
+            info("currency.properties entry for " + ctry +
+                        " ignored since exception encountered :" + ex.getMessage(), null);
             return;
         }
 
@@ -695,6 +728,26 @@
         setMainTableEntry(ctry.charAt(0), ctry.charAt(1), entry);
     }
 
+    private static boolean isPastCutoverDate(String s)
+            throws IndexOutOfBoundsException, NullPointerException, ParseException {
+        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT);
+        format.setTimeZone(TimeZone.getTimeZone("UTC"));
+        format.setLenient(false);
+        long time = format.parse(s.trim()).getTime();
+        return System.currentTimeMillis() > time;
+
+    }
+
+    private static int countOccurrences(String value, char match) {
+        int count = 0;
+        for (char c : value.toCharArray()) {
+            if (c == match) {
+               ++count;
+            }
+        }
+        return count;
+    }
+
     private static void info(String message, Throwable t) {
         PlatformLogger logger = PlatformLogger.getLogger("java.util.Currency");
         if (logger.isLoggable(PlatformLogger.INFO)) {
--- a/src/share/classes/java/util/HashMap.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/HashMap.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -230,7 +230,7 @@
 
         this.loadFactor = loadFactor;
         threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
-        table = new Entry[capacity];
+        table = new Entry<?,?>[capacity];
         init();
     }
 
@@ -1078,7 +1078,7 @@
             capacity <<= 1;
         }
 
-        table = new Entry[capacity];
+        table = new Entry<?,?>[capacity];
         threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
         init();  // Give subclass a chance to do its thing.
 
--- a/src/share/classes/java/util/JumboEnumSet.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/JumboEnumSet.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -121,6 +121,7 @@
             unseen = elements[0];
         }
 
+        @Override
         public boolean hasNext() {
             while (unseen == 0 && unseenIndex < elements.length - 1)
                 unseen = elements[++unseenIndex];
@@ -128,6 +129,7 @@
         }
 
         @Override
+        @SuppressWarnings("unchecked")
         public E next() {
             if (!hasNext())
                 throw new NoSuchElementException();
@@ -138,6 +140,7 @@
                                 + Long.numberOfTrailingZeros(lastReturned)];
         }
 
+        @Override
         public void remove() {
             if (lastReturned == 0)
                 throw new IllegalStateException();
--- a/src/share/classes/java/util/PriorityQueue.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/PriorityQueue.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -330,6 +330,7 @@
         return true;
     }
 
+    @SuppressWarnings("unchecked")
     public E peek() {
         if (size == 0)
             return null;
--- a/src/share/classes/java/util/PropertyPermission.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/PropertyPermission.java	Wed Sep 26 22:22:51 2012 -0700
@@ -246,7 +246,8 @@
             return mask;
         }
 
-        // Check against use of constants (used heavily within the JDK)
+        // Use object identity comparison against known-interned strings for
+        // performance benefit (these values are used heavily within the JDK).
         if (actions == SecurityConstants.PROPERTY_READ_ACTION) {
             return READ;
         } if (actions == SecurityConstants.PROPERTY_WRITE_ACTION) {
--- a/src/share/classes/java/util/PropertyResourceBundle.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/PropertyResourceBundle.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -125,6 +125,7 @@
      * @throws IOException if an I/O error occurs
      * @throws NullPointerException if <code>stream</code> is null
      */
+    @SuppressWarnings({"unchecked", "rawtypes"})
     public PropertyResourceBundle (InputStream stream) throws IOException {
         Properties properties = new Properties();
         properties.load(stream);
@@ -143,6 +144,7 @@
      * @throws NullPointerException if <code>reader</code> is null
      * @since 1.6
      */
+    @SuppressWarnings({"unchecked", "rawtypes"})
     public PropertyResourceBundle (Reader reader) throws IOException {
         Properties properties = new Properties();
         properties.load(reader);
--- a/src/share/classes/java/util/jar/JarVerifier.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/jar/JarVerifier.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -325,6 +325,7 @@
      * the given file in the jar.
      * @deprecated
      */
+    @Deprecated
     public java.security.cert.Certificate[] getCerts(String name)
     {
         return mapSignersToCertArray(getCodeSigners(name));
--- a/src/share/classes/java/util/jar/Pack200.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/jar/Pack200.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003,2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003,2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -726,13 +726,13 @@
     private static final String PACK_PROVIDER = "java.util.jar.Pack200.Packer";
     private static final String UNPACK_PROVIDER = "java.util.jar.Pack200.Unpacker";
 
-    private static Class packerImpl;
-    private static Class unpackerImpl;
+    private static Class<?> packerImpl;
+    private static Class<?> unpackerImpl;
 
     private synchronized static Object newInstance(String prop) {
         String implName = "(unknown)";
         try {
-            Class impl = (PACK_PROVIDER.equals(prop))? 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(
--- a/src/share/classes/java/util/zip/package.html	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/java/util/zip/package.html	Wed Sep 26 22:22:51 2012 -0700
@@ -2,7 +2,7 @@
 <html>
 <head>
 <!--
-Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
+Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 
 This code is free software; you can redistribute it and/or modify it
@@ -41,7 +41,7 @@
 
 </a>
 <ul>
-  <li><a href="ftp://ftp.uu.net/pub/archiving/zip/doc/appnote-970311-iz.zip">
+  <li><a href="http://www.info-zip.org/doc/appnote-19970311-iz.zip">
       Info-ZIP Application Note 970311
       </a> - a detailed description of the Info-ZIP format upon which
       the <code>java.util.zip</code> classes are based.
--- a/src/share/classes/javax/swing/text/DefaultCaret.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/javax/swing/text/DefaultCaret.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1503,9 +1503,14 @@
 
         if (caretWidth > -1) {
             return caretWidth;
+        } else {
+            Object property = UIManager.get("Caret.width");
+            if (property instanceof Integer) {
+                return ((Integer) property).intValue();
+            } else {
+                return 1;
+            }
         }
-
-        return 1;
     }
 
     // --- serialization ---------------------------------------------
--- a/src/share/classes/sun/awt/SunToolkit.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/awt/SunToolkit.java	Wed Sep 26 22:22:51 2012 -0700
@@ -506,40 +506,25 @@
         postEvent(targetToAppContext(e.getSource()), pe);
     }
 
-    protected static final Lock flushLock = new ReentrantLock();
-    private static boolean isFlushingPendingEvents = false;
-
     /*
      * Flush any pending events which haven't been posted to the AWT
      * EventQueue yet.
      */
     public static void flushPendingEvents()  {
-        flushLock.lock();
-        try {
-            // Don't call flushPendingEvents() recursively
-            if (!isFlushingPendingEvents) {
-                isFlushingPendingEvents = true;
-                AppContext appContext = AppContext.getAppContext();
-                PostEventQueue postEventQueue =
-                    (PostEventQueue)appContext.get(POST_EVENT_QUEUE_KEY);
-                if (postEventQueue != null) {
-                    postEventQueue.flush();
-                }
-            }
-        } finally {
-            isFlushingPendingEvents = false;
-            flushLock.unlock();
-        }
+        AppContext appContext = AppContext.getAppContext();
+        flushPendingEvents(appContext);
     }
 
-    public static boolean isPostEventQueueEmpty()  {
-        AppContext appContext = AppContext.getAppContext();
+    /*
+     * Flush the PostEventQueue for the right AppContext.
+     * The default flushPendingEvents only flushes the thread-local context,
+     * which is not always correct, c.f. 3746956
+     */
+    public static void flushPendingEvents(AppContext appContext) {
         PostEventQueue postEventQueue =
-            (PostEventQueue)appContext.get(POST_EVENT_QUEUE_KEY);
+                (PostEventQueue)appContext.get(POST_EVENT_QUEUE_KEY);
         if (postEventQueue != null) {
-            return postEventQueue.noEvents();
-        } else {
-            return true;
+            postEventQueue.flush();
         }
     }
 
@@ -2045,17 +2030,12 @@
     private EventQueueItem queueTail = null;
     private final EventQueue eventQueue;
 
-    // For the case when queue is cleared but events are not posted
-    private volatile boolean isFlushing = false;
+    private Thread flushThread = null;
 
     PostEventQueue(EventQueue eq) {
         eventQueue = eq;
     }
 
-    public synchronized boolean noEvents() {
-        return queueHead == null && !isFlushing;
-    }
-
     /*
      * Continually post pending AWTEvents to the Java EventQueue. The method
      * is synchronized to ensure the flush is completed before a new event
@@ -2066,20 +2046,48 @@
      * potentially lead to deadlock
      */
     public void flush() {
-        EventQueueItem tempQueue;
-        synchronized (this) {
-            tempQueue = queueHead;
-            queueHead = queueTail = null;
-            isFlushing = true;
-        }
+
+        Thread newThread = Thread.currentThread();
+
         try {
-            while (tempQueue != null) {
-                eventQueue.postEvent(tempQueue.event);
-                tempQueue = tempQueue.next;
+            EventQueueItem tempQueue;
+            synchronized (this) {
+                // Avoid method recursion
+                if (newThread == flushThread) {
+                    return;
+                }
+                // Wait for other threads' flushing
+                while (flushThread != null) {
+                    wait();
+                }
+                // Skip everything if queue is empty
+                if (queueHead == null) {
+                    return;
+                }
+                // Remember flushing thread
+                flushThread = newThread;
+
+                tempQueue = queueHead;
+                queueHead = queueTail = null;
+            }
+            try {
+                while (tempQueue != null) {
+                    eventQueue.postEvent(tempQueue.event);
+                    tempQueue = tempQueue.next;
+                }
+            }
+            finally {
+                // Only the flushing thread can get here
+                synchronized (this) {
+                    // Forget flushing thread, inform other pending threads
+                    flushThread = null;
+                    notifyAll();
+                }
             }
         }
-        finally {
-            isFlushing = false;
+        catch (InterruptedException e) {
+            // Couldn't allow exception go up, so at least recover the flag
+            newThread.interrupt();
         }
     }
 
--- a/src/share/classes/sun/awt/image/VolatileSurfaceManager.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/awt/image/VolatileSurfaceManager.java	Wed Sep 26 22:22:51 2012 -0700
@@ -333,11 +333,12 @@
             // using a SurfaceData that was created in a different
             // display mode.
             sdBackup = null;
-            sdCurrent = getBackupSurface();
             // Now, invalidate the old hardware-based SurfaceData
+            // Note that getBackupSurface may set sdAccel to null so we have to invalidate it before
             SurfaceData oldData = sdAccel;
             sdAccel = null;
             oldData.invalidate();
+            sdCurrent = getBackupSurface();
         }
         // Update graphicsConfig for the vImg in case it changed due to
         // this display change event
--- a/src/share/classes/sun/management/LockDataConverter.java	Fri Sep 21 12:22:52 2012 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,111 +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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.management;
-
-import java.lang.management.LockInfo;
-import java.lang.management.ThreadInfo;
-import javax.management.Attribute;
-import javax.management.StandardMBean;
-import javax.management.openmbean.CompositeData;
-
-/**
- * This MXBean is used for data conversion from LockInfo
- * to CompositeData (its mapped type) or vice versa.
- */
-class LockDataConverter extends StandardMBean
-         implements LockDataConverterMXBean {
-    private LockInfo      lockInfo;
-    private LockInfo[]    lockedSyncs;
-
-    LockDataConverter() {
-        super(LockDataConverterMXBean.class, true);
-        this.lockInfo = null;
-        this.lockedSyncs = null;
-    }
-
-    LockDataConverter(ThreadInfo ti) {
-        super(LockDataConverterMXBean.class, true);
-        this.lockInfo = ti.getLockInfo();
-        this.lockedSyncs = ti.getLockedSynchronizers();
-    }
-
-    public void setLockInfo(LockInfo l) {
-        this.lockInfo = l;
-    }
-
-    public LockInfo getLockInfo() {
-        return this.lockInfo;
-    }
-
-    public void setLockedSynchronizers(LockInfo[] l) {
-        this.lockedSyncs = l;
-    }
-
-    public LockInfo[] getLockedSynchronizers() {
-        return this.lockedSyncs;
-    }
-
-    // helper methods
-    CompositeData toLockInfoCompositeData() {
-        try {
-            return (CompositeData) getAttribute("LockInfo");
-        } catch (Exception e) {
-            throw new AssertionError(e);
-        }
-    }
-
-    CompositeData[] toLockedSynchronizersCompositeData() {
-        try {
-            return (CompositeData[]) getAttribute("LockedSynchronizers");
-        } catch (Exception e) {
-            throw new AssertionError(e);
-        }
-    }
-
-    LockInfo toLockInfo(CompositeData cd) {
-        try {
-            setAttribute(new Attribute("LockInfo", cd));
-        } catch (Exception e) {
-            throw new AssertionError(e);
-        }
-        return getLockInfo();
-    }
-
-    LockInfo[] toLockedSynchronizers(CompositeData[] cd) {
-        try {
-            setAttribute(new Attribute("LockedSynchronizers", cd));
-        } catch (Exception e) {
-            throw new AssertionError(e);
-        }
-        return getLockedSynchronizers();
-    }
-
-    static CompositeData toLockInfoCompositeData(LockInfo l) {
-        LockDataConverter ldc = new LockDataConverter();
-        ldc.setLockInfo(l);
-        return ldc.toLockInfoCompositeData();
-    }
-}
--- a/src/share/classes/sun/management/LockDataConverterMXBean.java	Fri Sep 21 12:22:52 2012 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.management;
-
-import java.lang.management.LockInfo;
-
-/**
- * This interface is used for data conversion from LockInfo
- * to CompositeData (its mapped type) or vice versa.
- */
-public interface LockDataConverterMXBean {
-    public void setLockInfo(LockInfo l);
-    public LockInfo getLockInfo();
-
-    public void setLockedSynchronizers(LockInfo[] l);
-    public LockInfo[] getLockedSynchronizers();
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/management/LockInfoCompositeData.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.management;
+
+import java.lang.management.LockInfo;
+import javax.management.openmbean.CompositeType;
+import javax.management.openmbean.CompositeData;
+import javax.management.openmbean.CompositeDataSupport;
+import javax.management.openmbean.OpenDataException;
+
+/**
+ * A CompositeData for LockInfo for the local management support.
+ * This class avoids the performance penalty paid to the
+ * construction of a CompositeData use in the local case.
+ */
+public class LockInfoCompositeData extends LazyCompositeData {
+    private final LockInfo lock;
+
+    private LockInfoCompositeData(LockInfo li) {
+        this.lock = li;
+    }
+
+    public LockInfo getLockInfo() {
+        return lock;
+    }
+
+    public static CompositeData toCompositeData(LockInfo li) {
+        if (li == null) {
+            return null;
+        }
+
+        LockInfoCompositeData licd = new LockInfoCompositeData(li);
+        return licd.getCompositeData();
+    }
+
+    protected CompositeData getCompositeData() {
+        // CONTENTS OF THIS ARRAY MUST BE SYNCHRONIZED WITH
+        // lockInfoItemNames!
+        final Object[] lockInfoItemValues = {
+            new String(lock.getClassName()),
+            new Integer(lock.getIdentityHashCode()),
+        };
+
+        try {
+            return new CompositeDataSupport(lockInfoCompositeType,
+                                            lockInfoItemNames,
+                                            lockInfoItemValues);
+        } catch (OpenDataException e) {
+            // Should never reach here
+            throw Util.newException(e);
+        }
+    }
+
+    private static final CompositeType lockInfoCompositeType;
+    static {
+        try {
+            lockInfoCompositeType = (CompositeType)
+                MappedMXBeanType.toOpenType(LockInfo.class);
+        } catch (OpenDataException e) {
+            // Should never reach here
+            throw Util.newException(e);
+        }
+    }
+
+    static CompositeType getLockInfoCompositeType() {
+        return lockInfoCompositeType;
+    }
+
+    private static final String CLASS_NAME         = "className";
+    private static final String IDENTITY_HASH_CODE = "identityHashCode";
+    private static final String[] lockInfoItemNames = {
+        CLASS_NAME,
+        IDENTITY_HASH_CODE,
+    };
+
+    /*
+     * Returns a LockInfo object mapped from the given CompositeData.
+     */
+    public static LockInfo toLockInfo(CompositeData cd) {
+        if (cd == null) {
+            throw new NullPointerException("Null CompositeData");
+        }
+
+        if (!isTypeMatched(lockInfoCompositeType, cd.getCompositeType())) {
+            throw new IllegalArgumentException(
+                "Unexpected composite type for LockInfo");
+        }
+
+        String className = getString(cd, CLASS_NAME);
+        int identityHashCode = getInt(cd, IDENTITY_HASH_CODE);
+        return new LockInfo(className, identityHashCode);
+    }
+
+    private static final long serialVersionUID = -6374759159749014052L;
+}
--- a/src/share/classes/sun/management/MappedMXBeanType.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/management/MappedMXBeanType.java	Wed Sep 26 22:22:51 2012 -0700
@@ -703,7 +703,7 @@
                 if (data instanceof java.lang.management.MonitorInfo) {
                     return MonitorInfoCompositeData.toCompositeData((MonitorInfo) data);
                 }
-                return LockDataConverter.toLockInfoCompositeData((LockInfo) data);
+                return LockInfoCompositeData.toCompositeData((LockInfo) data);
             }
 
             if (data instanceof MemoryNotificationInfo) {
--- a/src/share/classes/sun/management/MonitorInfoCompositeData.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/management/MonitorInfoCompositeData.java	Wed Sep 26 22:22:51 2012 -0700
@@ -59,7 +59,7 @@
 
         int len = monitorInfoItemNames.length;
         Object[] values = new Object[len];
-        CompositeData li = LockDataConverter.toLockInfoCompositeData(lock);
+        CompositeData li = LockInfoCompositeData.toCompositeData(lock);
 
         for (int i = 0; i < len; i++) {
             String item = monitorInfoItemNames[i];
--- a/src/share/classes/sun/management/ThreadInfoCompositeData.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/management/ThreadInfoCompositeData.java	Wed Sep 26 22:22:51 2012 -0700
@@ -85,11 +85,18 @@
         }
 
         // Convert MonitorInfo[] and LockInfo[] to CompositeData[]
-        LockDataConverter converter = new LockDataConverter(threadInfo);
-        CompositeData lockInfoData = converter.toLockInfoCompositeData();
-        CompositeData[] lockedSyncsData = converter.toLockedSynchronizersCompositeData();
+        CompositeData lockInfoData =
+            LockInfoCompositeData.toCompositeData(threadInfo.getLockInfo());
 
-        // Convert MonitorInfo[] to CompositeData[]
+        // Convert LockInfo[] and MonitorInfo[] to CompositeData[]
+        LockInfo[] lockedSyncs = threadInfo.getLockedSynchronizers();
+        CompositeData[] lockedSyncsData =
+            new CompositeData[lockedSyncs.length];
+        for (int i = 0; i < lockedSyncs.length; i++) {
+            LockInfo li = lockedSyncs[i];
+            lockedSyncsData[i] = LockInfoCompositeData.toCompositeData(li);
+        }
+
         MonitorInfo[] lockedMonitors = threadInfo.getLockedMonitors();
         CompositeData[] lockedMonitorsData =
             new CompositeData[lockedMonitors.length];
@@ -98,7 +105,6 @@
             lockedMonitorsData[i] = MonitorInfoCompositeData.toCompositeData(mi);
         }
 
-
         // CONTENTS OF THIS ARRAY MUST BE SYNCHRONIZED WITH
         // threadInfoItemNames!
         final Object[] threadInfoItemValues = {
@@ -216,11 +222,11 @@
         // with it.  So we can get the CompositeType representing LockInfo
         // from a mapped CompositeData for any LockInfo object.
         // Thus we construct a random LockInfo object and pass it
-        // to LockDataConverter to do the conversion.
+        // to LockInfoCompositeData to do the conversion.
         Object o = new Object();
         LockInfo li = new LockInfo(o.getClass().getName(),
                                    System.identityHashCode(o));
-        CompositeData cd = LockDataConverter.toLockInfoCompositeData(li);
+        CompositeData cd = LockInfoCompositeData.toCompositeData(li);
         lockInfoCompositeType = cd.getCompositeType();
     }
 
@@ -315,9 +321,8 @@
 
     // 6.0 new attributes
     public LockInfo lockInfo() {
-        LockDataConverter converter = new LockDataConverter();
         CompositeData lockInfoData = (CompositeData) cdata.get(LOCK_INFO);
-        return converter.toLockInfo(lockInfoData);
+        return LockInfo.from(lockInfoData);
     }
 
     public MonitorInfo[] lockedMonitors() {
@@ -336,13 +341,17 @@
     }
 
     public LockInfo[] lockedSynchronizers() {
-        LockDataConverter converter = new LockDataConverter();
         CompositeData[] lockedSyncsData =
             (CompositeData[]) cdata.get(LOCKED_SYNCS);
 
         // The LockedSynchronizers item cannot be null, but if it is we will
         // get a NullPointerException when we ask for its length.
-        return converter.toLockedSynchronizers(lockedSyncsData);
+        LockInfo[] locks = new LockInfo[lockedSyncsData.length];
+        for (int i = 0; i < lockedSyncsData.length; i++) {
+            CompositeData cdi = lockedSyncsData[i];
+            locks[i] = LockInfo.from(cdi);
+        }
+        return locks;
     }
 
     /** Validate if the input CompositeData has the expected
--- a/src/share/classes/sun/security/ec/ECParameters.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/ec/ECParameters.java	Wed Sep 26 22:22:51 2012 -0700
@@ -87,8 +87,10 @@
         if ((data.length == 0) || (data[0] != 4)) {
             throw new IOException("Only uncompressed point format supported");
         }
-        int n = data.length / 2;
-        if (n > ((curve.getField().getFieldSize() + 7 ) >> 3)) {
+        // Per ANSI X9.62, an encoded point is a 1 byte type followed by
+        // ceiling(log base 2 field-size / 8) bytes of x and the same of y.
+        int n = (data.length - 1) / 2;
+        if (n != ((curve.getField().getFieldSize() + 7 ) >> 3)) {
             throw new IOException("Point does not match field size");
         }
         byte[] xb = new byte[n];
--- a/src/share/classes/sun/security/provider/certpath/AlgorithmChecker.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/AlgorithmChecker.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -259,8 +259,7 @@
             }
 
             // Inherit key parameters from previous key
-            if (currPubKey instanceof DSAPublicKey &&
-                ((DSAPublicKey)currPubKey).getParams() == null) {
+            if (PKIX.isDSAPublicKeyWithoutParams(currPubKey)) {
                 // Inherit DSA parameters from previous key
                 if (!(prevPubKey instanceof DSAPublicKey)) {
                     throw new CertPathValidatorException("Input key is not " +
--- a/src/share/classes/sun/security/provider/certpath/BasicChecker.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/BasicChecker.java	Wed Sep 26 22:22:51 2012 -0700
@@ -101,9 +101,7 @@
     public void init(boolean forward) throws CertPathValidatorException {
         if (!forward) {
             prevPubKey = trustedPubKey;
-            if (prevPubKey instanceof DSAPublicKey &&
-                ((DSAPublicKey)prevPubKey).getParams() == null)
-            {
+            if (PKIX.isDSAPublicKeyWithoutParams(prevPubKey)) {
                 // If TrustAnchor is a DSA public key and it has no params, it
                 // cannot be used to verify the signature of the first cert,
                 // so throw exception
@@ -248,8 +246,7 @@
                 currCert.getSubjectX500Principal() + "; serial#: " +
                 currCert.getSerialNumber().toString());
         }
-        if (cKey instanceof DSAPublicKey &&
-            ((DSAPublicKey)cKey).getParams() == null) {
+        if (PKIX.isDSAPublicKeyWithoutParams(cKey)) {
             // cKey needs to inherit DSA parameters from prev key
             cKey = makeInheritedParamsKey(cKey, prevPubKey);
             if (debug != null) debug.println("BasicChecker.updateState Made " +
--- a/src/share/classes/sun/security/provider/certpath/CertStoreHelper.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/CertStoreHelper.java	Wed Sep 26 22:22:51 2012 -0700
@@ -35,6 +35,7 @@
 import java.security.PrivilegedActionException;
 import java.security.PrivilegedExceptionAction;
 import java.security.cert.CertStore;
+import java.security.cert.CertStoreException;
 import java.security.cert.X509CertSelector;
 import java.security.cert.X509CRLSelector;
 import javax.security.auth.x500.X500Principal;
@@ -96,6 +97,25 @@
         }
     }
 
+    static boolean isCausedByNetworkIssue(String type, CertStoreException cse) {
+        switch (type) {
+            case "LDAP":
+            case "SSLServer":
+                try {
+                    CertStoreHelper csh = CertStoreHelper.getInstance(type);
+                    return csh.isCausedByNetworkIssue(cse);
+                } catch (NoSuchAlgorithmException nsae) {
+                    return false;
+                }
+            case "URI":
+                Throwable t = cse.getCause();
+                return (t != null && t instanceof IOException);
+            default:
+                // we don't know about any other remote CertStore types
+                return false;
+        }
+    }
+
     /**
      * Returns a CertStore using the given URI as parameters.
      */
@@ -119,4 +139,10 @@
                          Collection<X500Principal> certIssuers,
                          String dn)
         throws IOException;
+
+    /**
+     * Returns true if the cause of the CertStoreException is a network
+     * related issue.
+     */
+    public abstract boolean isCausedByNetworkIssue(CertStoreException e);
 }
--- a/src/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java	Wed Sep 26 22:22:51 2012 -0700
@@ -116,12 +116,17 @@
     /**
      * Download CRLs from the given distribution point, verify and return them.
      * See the top of the class for current limitations.
+     *
+     * @throws CertStoreException if there is an error retrieving the CRLs
+     *         from one of the GeneralNames and no other CRLs are retrieved from
+     *         the other GeneralNames. If more than one GeneralName throws an
+     *         exception then the one from the last GeneralName is thrown.
      */
     private static Collection<X509CRL> getCRLs(X509CRLSelector selector,
         X509CertImpl certImpl, DistributionPoint point, boolean[] reasonsMask,
         boolean signFlag, PublicKey prevKey, String provider,
         List<CertStore> certStores, Set<TrustAnchor> trustAnchors,
-        Date validity) {
+        Date validity) throws CertStoreException {
 
         // check for full name
         GeneralNames fullName = point.getFullName();
@@ -149,24 +154,33 @@
                 return Collections.emptySet();
             }
         }
-        Collection<X509CRL> possibleCRLs = new ArrayList<X509CRL>();
-        Collection<X509CRL> crls = new ArrayList<X509CRL>(2);
+        Collection<X509CRL> possibleCRLs = new ArrayList<>();
+        CertStoreException savedCSE = null;
         for (Iterator<GeneralName> t = fullName.iterator(); t.hasNext(); ) {
-            GeneralName name = t.next();
-            if (name.getType() == GeneralNameInterface.NAME_DIRECTORY) {
-                X500Name x500Name = (X500Name) name.getName();
-                possibleCRLs.addAll(
-                    getCRLs(x500Name, certImpl.getIssuerX500Principal(),
-                            certStores));
-            } else if (name.getType() == GeneralNameInterface.NAME_URI) {
-                URIName uriName = (URIName)name.getName();
-                X509CRL crl = getCRL(uriName);
-                if (crl != null) {
-                    possibleCRLs.add(crl);
+            try {
+                GeneralName name = t.next();
+                if (name.getType() == GeneralNameInterface.NAME_DIRECTORY) {
+                    X500Name x500Name = (X500Name) name.getName();
+                    possibleCRLs.addAll(
+                        getCRLs(x500Name, certImpl.getIssuerX500Principal(),
+                                certStores));
+                } else if (name.getType() == GeneralNameInterface.NAME_URI) {
+                    URIName uriName = (URIName)name.getName();
+                    X509CRL crl = getCRL(uriName);
+                    if (crl != null) {
+                        possibleCRLs.add(crl);
+                    }
                 }
+            } catch (CertStoreException cse) {
+                savedCSE = cse;
             }
         }
+        // only throw CertStoreException if no CRLs are retrieved
+        if (possibleCRLs.isEmpty() && savedCSE != null) {
+            throw savedCSE;
+        }
 
+        Collection<X509CRL> crls = new ArrayList<>(2);
         for (X509CRL crl : possibleCRLs) {
             try {
                 // make sure issuer is not set
@@ -191,34 +205,43 @@
     /**
      * Download CRL from given URI.
      */
-    private static X509CRL getCRL(URIName name) {
+    private static X509CRL getCRL(URIName name) throws CertStoreException {
         URI uri = name.getURI();
         if (debug != null) {
             debug.println("Trying to fetch CRL from DP " + uri);
         }
+        CertStore ucs = null;
         try {
-            CertStore ucs = URICertStore.getInstance
+            ucs = URICertStore.getInstance
                 (new URICertStore.URICertStoreParameters(uri));
-            Collection<? extends CRL> crls = ucs.getCRLs(null);
-            if (crls.isEmpty()) {
-                return null;
-            } else {
-                return (X509CRL) crls.iterator().next();
+        } catch (InvalidAlgorithmParameterException |
+                 NoSuchAlgorithmException e) {
+            if (debug != null) {
+                debug.println("Can't create URICertStore: " + e.getMessage());
             }
-        } catch (Exception e) {
-            if (debug != null) {
-                debug.println("Exception getting CRL from CertStore: " + e);
-                e.printStackTrace();
-            }
+            return null;
         }
-        return null;
+
+        Collection<? extends CRL> crls = ucs.getCRLs(null);
+        if (crls.isEmpty()) {
+            return null;
+        } else {
+            return (X509CRL) crls.iterator().next();
+        }
     }
 
     /**
      * Fetch CRLs from certStores.
+     *
+     * @throws CertStoreException if there is an error retrieving the CRLs from
+     *         one of the CertStores and no other CRLs are retrieved from
+     *         the other CertStores. If more than one CertStore throws an
+     *         exception then the one from the last CertStore is thrown.
      */
     private static Collection<X509CRL> getCRLs(X500Name name,
-        X500Principal certIssuer, List<CertStore> certStores)
+                                               X500Principal certIssuer,
+                                               List<CertStore> certStores)
+        throws CertStoreException
     {
         if (debug != null) {
             debug.println("Trying to fetch CRL from DP " + name);
@@ -227,21 +250,27 @@
         xcs.addIssuer(name.asX500Principal());
         xcs.addIssuer(certIssuer);
         Collection<X509CRL> crls = new ArrayList<>();
+        CertStoreException savedCSE = null;
         for (CertStore store : certStores) {
             try {
                 for (CRL crl : store.getCRLs(xcs)) {
                     crls.add((X509CRL)crl);
                 }
             } catch (CertStoreException cse) {
-                // don't add the CRL
                 if (debug != null) {
-                    debug.println("Non-fatal exception while retrieving " +
+                    debug.println("Exception while retrieving " +
                         "CRLs: " + cse);
                     cse.printStackTrace();
                 }
+                savedCSE = new PKIX.CertStoreTypeException(store.getType(),cse);
             }
         }
-        return crls;
+        // only throw CertStoreException if no CRLs are retrieved
+        if (crls.isEmpty() && savedCSE != null) {
+            throw savedCSE;
+        } else {
+            return crls;
+        }
     }
 
     /**
--- a/src/share/classes/sun/security/provider/certpath/ForwardBuilder.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/ForwardBuilder.java	Wed Sep 26 22:22:51 2012 -0700
@@ -369,20 +369,21 @@
         boolean add = false;
         for (AccessDescription ad : adList) {
             CertStore cs = URICertStore.getInstance(ad);
-            try {
-                if (certs.addAll((Collection<X509Certificate>)
-                    cs.getCertificates(caSelector))) {
-                    add = true;
-                    if (!searchAllCertStores) {
-                        return true;
+            if (cs != null) {
+                try {
+                    if (certs.addAll((Collection<X509Certificate>)
+                        cs.getCertificates(caSelector))) {
+                        add = true;
+                        if (!searchAllCertStores) {
+                            return true;
+                        }
+                    }
+                } catch (CertStoreException cse) {
+                    if (debug != null) {
+                        debug.println("exception getting certs from CertStore:");
+                        cse.printStackTrace();
                     }
                 }
-            } catch (CertStoreException cse) {
-                if (debug != null) {
-                    debug.println("exception getting certs from CertStore:");
-                    cse.printStackTrace();
-                }
-                continue;
             }
         }
         return add;
@@ -816,36 +817,36 @@
                 } else {
                     continue;
                 }
-            } else {
-                X500Principal principal = anchor.getCA();
-                PublicKey publicKey = anchor.getCAPublicKey();
+            }
+            X500Principal principal = anchor.getCA();
+            PublicKey publicKey = anchor.getCAPublicKey();
 
-                if (principal != null && publicKey != null &&
-                        principal.equals(cert.getSubjectX500Principal())) {
-                    if (publicKey.equals(cert.getPublicKey())) {
-                        // the cert itself is a trust anchor
-                        this.trustAnchor = anchor;
-                        return true;
-                    }
-                    // else, it is a self-issued certificate of the anchor
+            if (principal != null && publicKey != null &&
+                    principal.equals(cert.getSubjectX500Principal())) {
+                if (publicKey.equals(cert.getPublicKey())) {
+                    // the cert itself is a trust anchor
+                    this.trustAnchor = anchor;
+                    return true;
                 }
+                // else, it is a self-issued certificate of the anchor
+            }
 
-                // Check subject/issuer name chaining
-                if (principal == null ||
-                        !principal.equals(cert.getIssuerX500Principal())) {
-                    continue;
-                }
+            // Check subject/issuer name chaining
+            if (principal == null ||
+                    !principal.equals(cert.getIssuerX500Principal())) {
+                continue;
+            }
+
+            // skip anchor if it contains a DSA key with no DSA params
+            if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
+                continue;
             }
 
             /*
              * Check signature
              */
             try {
-                // NOTE: the DSA public key in the buildParams may lack
-                // parameters, yet there is no key to inherit the parameters
-                // from.  This is probably such a rare case that it is not worth
-                // trying to detect the situation earlier.
-                cert.verify(anchor.getCAPublicKey(), buildParams.sigProvider());
+                cert.verify(publicKey, buildParams.sigProvider());
             } catch (InvalidKeyException ike) {
                 if (debug != null) {
                     debug.println("ForwardBuilder.isPathCompleted() invalid "
--- a/src/share/classes/sun/security/provider/certpath/ForwardState.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/ForwardState.java	Wed Sep 26 22:22:51 2012 -0700
@@ -26,12 +26,10 @@
 package sun.security.provider.certpath;
 
 import java.io.IOException;
-import java.security.PublicKey;
 import java.security.cert.CertificateException;
 import java.security.cert.CertPathValidatorException;
 import java.security.cert.PKIXCertPathChecker;
 import java.security.cert.X509Certificate;
-import java.security.interfaces.DSAPublicKey;
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
@@ -169,9 +167,7 @@
         X509CertImpl icert = X509CertImpl.toImpl(cert);
 
         /* see if certificate key has null parameters */
-        PublicKey newKey = icert.getPublicKey();
-        if (newKey instanceof DSAPublicKey &&
-            ((DSAPublicKey)newKey).getParams() == null) {
+        if (PKIX.isDSAPublicKeyWithoutParams(icert.getPublicKey())) {
             keyParamsNeededFlag = true;
         }
 
--- a/src/share/classes/sun/security/provider/certpath/OCSP.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/OCSP.java	Wed Sep 26 22:22:51 2012 -0700
@@ -335,8 +335,8 @@
     static class NetworkFailureException extends CertPathValidatorException {
         private static final long serialVersionUID = 0l;
 
-        private NetworkFailureException(IOException ioe) {
-            super(ioe);
+        NetworkFailureException(Throwable t) {
+            super(t);
         }
 
         @Override
--- a/src/share/classes/sun/security/provider/certpath/PKIX.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/PKIX.java	Wed Sep 26 22:22:51 2012 -0700
@@ -26,7 +26,9 @@
 
 import java.security.InvalidAlgorithmParameterException;
 import java.security.KeyStore;
+import java.security.PublicKey;
 import java.security.cert.*;
+import java.security.interfaces.DSAPublicKey;
 import java.util.*;
 import javax.security.auth.x500.X500Principal;
 
@@ -42,6 +44,11 @@
 
     private PKIX() { }
 
+    static boolean isDSAPublicKeyWithoutParams(PublicKey publicKey) {
+        return (publicKey instanceof DSAPublicKey &&
+               ((DSAPublicKey)publicKey).getParams() == null);
+    }
+
     static ValidatorParams checkParams(CertPath cp, CertPathParameters params)
         throws InvalidAlgorithmParameterException
     {
@@ -271,6 +278,24 @@
     }
 
     /**
+     * A CertStoreException with additional information about the type of
+     * CertStore that generated the exception.
+     */
+    static class CertStoreTypeException extends CertStoreException {
+        private static final long serialVersionUID = 7463352639238322556L;
+
+        private final String type;
+
+        CertStoreTypeException(String type, CertStoreException cse) {
+            super(cse.getMessage(), cse.getCause());
+            this.type = type;
+        }
+        String getType() {
+            return type;
+        }
+    }
+
+    /**
      * Comparator that orders CertStores so that local CertStores come before
      * remote CertStores.
      */
--- a/src/share/classes/sun/security/provider/certpath/ReverseState.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/ReverseState.java	Wed Sep 26 22:22:51 2012 -0700
@@ -32,7 +32,6 @@
 import java.security.cert.PKIXCertPathChecker;
 import java.security.cert.TrustAnchor;
 import java.security.cert.X509Certificate;
-import java.security.interfaces.DSAPublicKey;
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
@@ -287,8 +286,7 @@
         /* check for key needing to inherit alg parameters */
         X509CertImpl icert = X509CertImpl.toImpl(cert);
         PublicKey newKey = cert.getPublicKey();
-        if (newKey instanceof DSAPublicKey &&
-            (((DSAPublicKey)newKey).getParams() == null)) {
+        if (PKIX.isDSAPublicKeyWithoutParams(newKey)) {
             newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey);
         }
 
--- a/src/share/classes/sun/security/provider/certpath/RevocationChecker.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/RevocationChecker.java	Wed Sep 26 22:22:51 2012 -0700
@@ -38,7 +38,6 @@
 import java.security.cert.CertPathValidatorException.BasicReason;
 import java.security.cert.Extension;
 import java.security.cert.*;
-import java.security.interfaces.DSAPublicKey;
 import java.util.Arrays;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -50,7 +49,7 @@
 import javax.security.auth.x500.X500Principal;
 
 import static sun.security.provider.certpath.OCSP.*;
-import sun.security.provider.certpath.PKIX.ValidatorParams;
+import static sun.security.provider.certpath.PKIX.*;
 import sun.security.action.GetPropertyAction;
 import sun.security.x509.*;
 import static sun.security.x509.PKIXExtensions.*;
@@ -406,8 +405,7 @@
 
         // Make new public key if parameters are missing
         PublicKey pubKey = cert.getPublicKey();
-        if (pubKey instanceof DSAPublicKey &&
-            ((DSAPublicKey)pubKey).getParams() == null) {
+        if (PKIX.isDSAPublicKeyWithoutParams(pubKey)) {
             // pubKey needs to inherit DSA parameters from prev key
             pubKey = BasicChecker.makeInheritedParamsKey(pubKey, prevPubKey);
         }
@@ -458,14 +456,23 @@
         sel.setCertificateChecking(cert);
         CertPathHelper.setDateAndTime(sel, params.date(), MAX_CLOCK_SKEW);
 
-        // First, check cached CRLs
+        // First, check user-specified CertStores
+        NetworkFailureException nfe = null;
         for (CertStore store : certStores) {
             try {
                 for (CRL crl : store.getCRLs(sel)) {
                     possibleCRLs.add((X509CRL)crl);
                 }
             } catch (CertStoreException e) {
-                // XXX ignore?
+                if (debug != null) {
+                    debug.println("RevocationChecker.checkCRLs() " +
+                                  "CertStoreException: " + e.getMessage());
+                }
+                if (softFail && nfe == null &&
+                    CertStoreHelper.isCausedByNetworkIssue(store.getType(),e)) {
+                    // save this exception, we may need to throw it later
+                    nfe = new NetworkFailureException(e);
+                }
             }
         }
 
@@ -504,9 +511,12 @@
                                         reasonsMask, anchors, params.date()));
                 }
             } catch (CertStoreException e) {
-                if (debug != null) {
-                    debug.println("RevocationChecker.checkCRLs() " +
-                                  "unexpected exception: " + e.getMessage());
+                if (softFail && e instanceof CertStoreTypeException) {
+                    CertStoreTypeException cste = (CertStoreTypeException)e;
+                    if (CertStoreHelper.isCausedByNetworkIssue(cste.getType(),
+                                                               e)) {
+                        throw new NetworkFailureException(e);
+                    }
                 }
                 throw new CertPathValidatorException(e);
             }
@@ -516,10 +526,28 @@
                 checkApprovedCRLs(cert, approvedCRLs);
             } else {
                 if (allowSeparateKey) {
-                    verifyWithSeparateSigningKey(cert, prevKey, signFlag,
-                                                 stackedCerts);
-                    return;
+                    try {
+                        verifyWithSeparateSigningKey(cert, prevKey, signFlag,
+                                                     stackedCerts);
+                        return;
+                    } catch (CertPathValidatorException cpve) {
+                        if (nfe != null) {
+                            // if a network issue previously prevented us from
+                            // retrieving a CRL from one of the user-specified
+                            // CertStores and SOFT_FAIL is enabled, throw it now
+                            // so it can be handled appropriately
+                            throw nfe;
+                        }
+                        throw cpve;
+                    }
                 } else {
+                    if (nfe != null) {
+                        // if a network issue previously prevented us from
+                        // retrieving a CRL from one of the user-specified
+                        // CertStores and SOFT_FAIL is enabled, throw it now
+                        // so it can be handled appropriately
+                        throw nfe;
+                    }
                     throw new CertPathValidatorException
                     ("Could not determine revocation status", null, null, -1,
                      BasicReason.UNDETERMINED_REVOCATION_STATUS);
--- a/src/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java	Wed Sep 26 22:22:51 2012 -0700
@@ -31,7 +31,6 @@
 import java.security.PublicKey;
 import java.security.cert.*;
 import java.security.cert.PKIXReason;
-import java.security.interfaces.DSAPublicKey;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -242,6 +241,15 @@
                 break;
             }
 
+            // skip anchor if it contains a DSA key with no DSA params
+            X509Certificate trustedCert = anchor.getTrustedCert();
+            PublicKey pubKey = trustedCert != null ? trustedCert.getPublicKey()
+                                                   : anchor.getCAPublicKey();
+
+            if (PKIX.isDSAPublicKeyWithoutParams(pubKey)) {
+                continue;
+            }
+
             /* Initialize current state */
             currentState.initState(buildParams);
             currentState.updateState(anchor, buildParams);
@@ -705,9 +713,7 @@
                  * Extract and save the final target public key
                  */
                 finalPublicKey = cert.getPublicKey();
-                if (finalPublicKey instanceof DSAPublicKey &&
-                    ((DSAPublicKey)finalPublicKey).getParams() == null)
-                {
+                if (PKIX.isDSAPublicKeyWithoutParams(finalPublicKey)) {
                     finalPublicKey =
                         BasicChecker.makeInheritedParamsKey
                             (finalPublicKey, currentState.pubKey);
--- a/src/share/classes/sun/security/provider/certpath/URICertStore.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/URICertStore.java	Wed Sep 26 22:22:51 2012 -0700
@@ -340,7 +340,11 @@
             // Fetch the CRLs via LDAP. LDAPCertStore has its own
             // caching mechanism, see the class description for more info.
             // Safe cast since xsel is an X509 certificate selector.
-            return (Collection<X509CRL>) ldapCertStore.getCRLs(xsel);
+            try {
+                return (Collection<X509CRL>) ldapCertStore.getCRLs(xsel);
+            } catch (CertStoreException cse) {
+                throw new PKIX.CertStoreTypeException("LDAP", cse);
+            }
         }
 
         // Return the CRLs for this entry. It returns the cached value
@@ -391,11 +395,12 @@
                 debug.println("Exception fetching CRL:");
                 e.printStackTrace();
             }
+            // exception, forget previous values
+            lastModified = 0;
+            crl = null;
+            throw new PKIX.CertStoreTypeException("URI",
+                                                  new CertStoreException(e));
         }
-        // exception, forget previous values
-        lastModified = 0;
-        crl = null;
-        return Collections.emptyList();
     }
 
     /**
--- a/src/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreHelper.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreHelper.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,15 +25,18 @@
 
 package sun.security.provider.certpath.ldap;
 
+import java.io.IOException;
 import java.net.URI;
 import java.util.Collection;
 import java.security.NoSuchAlgorithmException;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.cert.CertStore;
+import java.security.cert.CertStoreException;
 import java.security.cert.X509CertSelector;
 import java.security.cert.X509CRLSelector;
+import javax.naming.CommunicationException;
+import javax.naming.ServiceUnavailableException;
 import javax.security.auth.x500.X500Principal;
-import java.io.IOException;
 
 import sun.security.provider.certpath.CertStoreHelper;
 
@@ -68,4 +71,11 @@
     {
         return new LDAPCertStore.LDAPCRLSelector(selector, certIssuers, ldapDN);
     }
+
+    @Override
+    public boolean isCausedByNetworkIssue(CertStoreException e) {
+        Throwable t = e.getCause();
+        return (t != null && (t instanceof ServiceUnavailableException ||
+                              t instanceof CommunicationException));
+    }
 }
--- a/src/share/classes/sun/security/provider/certpath/ssl/SSLServerCertStoreHelper.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/ssl/SSLServerCertStoreHelper.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,15 +25,16 @@
 
 package sun.security.provider.certpath.ssl;
 
+import java.io.IOException;
 import java.net.URI;
-import java.util.Collection;
 import java.security.NoSuchAlgorithmException;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.cert.CertStore;
+import java.security.cert.CertStoreException;
 import java.security.cert.X509CertSelector;
 import java.security.cert.X509CRLSelector;
+import java.util.Collection;
 import javax.security.auth.x500.X500Principal;
-import java.io.IOException;
 
 import sun.security.provider.certpath.CertStoreHelper;
 
@@ -66,4 +67,10 @@
     {
         throw new UnsupportedOperationException();
     }
+
+    @Override
+    public boolean isCausedByNetworkIssue(CertStoreException e) {
+        Throwable t = e.getCause();
+        return (t != null && t instanceof IOException);
+    }
 }
--- a/src/share/classes/sun/security/ssl/SSLContextImpl.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/ssl/SSLContextImpl.java	Wed Sep 26 22:22:51 2012 -0700
@@ -266,7 +266,7 @@
     }
 
     // Get suported CipherSuiteList.
-    CipherSuiteList getSuportedCipherSuiteList() {
+    CipherSuiteList getSupportedCipherSuiteList() {
         // The maintenance of cipher suites needs to be synchronized.
         synchronized (this) {
             // Clear cache of available ciphersuites.
--- a/src/share/classes/sun/security/ssl/SSLEngineImpl.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/ssl/SSLEngineImpl.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1978,7 +1978,7 @@
      * @return an array of cipher suite names
      */
     public String[] getSupportedCipherSuites() {
-        return sslContext.getSuportedCipherSuiteList().toStringArray();
+        return sslContext.getSupportedCipherSuiteList().toStringArray();
     }
 
     /**
--- a/src/share/classes/sun/security/ssl/SSLServerSocketFactoryImpl.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/ssl/SSLServerSocketFactoryImpl.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -113,7 +113,7 @@
      * @return an array of cipher suite names
      */
     public String[] getSupportedCipherSuites() {
-        return context.getSuportedCipherSuiteList().toStringArray();
+        return context.getSupportedCipherSuiteList().toStringArray();
     }
 
 }
--- a/src/share/classes/sun/security/ssl/SSLServerSocketImpl.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/ssl/SSLServerSocketImpl.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -168,7 +168,7 @@
      * @return an array of cipher suite names
      */
     public String[] getSupportedCipherSuites() {
-        return sslContext.getSuportedCipherSuiteList().toStringArray();
+        return sslContext.getSupportedCipherSuiteList().toStringArray();
     }
 
     /**
--- a/src/share/classes/sun/security/ssl/SSLSocketFactoryImpl.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/ssl/SSLSocketFactoryImpl.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -177,6 +177,6 @@
      * certain kinds of certificates to use certain cipher suites.
      */
     public String[] getSupportedCipherSuites() {
-        return context.getSuportedCipherSuiteList().toStringArray();
+        return context.getSupportedCipherSuiteList().toStringArray();
     }
 }
--- a/src/share/classes/sun/security/ssl/SSLSocketImpl.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/ssl/SSLSocketImpl.java	Wed Sep 26 22:22:51 2012 -0700
@@ -2353,7 +2353,7 @@
      * @return an array of cipher suite names
      */
     public String[] getSupportedCipherSuites() {
-        return sslContext.getSuportedCipherSuiteList().toStringArray();
+        return sslContext.getSupportedCipherSuiteList().toStringArray();
     }
 
     /**
--- a/src/share/classes/sun/security/util/Debug.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/util/Debug.java	Wed Sep 26 22:22:51 2012 -0700
@@ -70,15 +70,22 @@
         System.err.println();
         System.err.println("all           turn on all debugging");
         System.err.println("access        print all checkPermission results");
+        System.err.println("certpath      PKIX CertPathBuilder and");
+        System.err.println("              CertPathValidator debugging");
         System.err.println("combiner      SubjectDomainCombiner debugging");
         System.err.println("gssloginconfig");
+        System.err.println("              GSS LoginConfigImpl debugging");
         System.err.println("configfile    JAAS ConfigFile loading");
         System.err.println("configparser  JAAS ConfigFile parsing");
-        System.err.println("              GSS LoginConfigImpl debugging");
         System.err.println("jar           jar verification");
         System.err.println("logincontext  login context results");
+        System.err.println("jca           JCA engine class debugging");
         System.err.println("policy        loading and granting");
         System.err.println("provider      security provider debugging");
+        System.err.println("pkcs11        PKCS11 session manager debugging");
+        System.err.println("pkcs11keystore");
+        System.err.println("              PKCS11 KeyStore debugging");
+        System.err.println("sunpkcs11     SunPKCS11 provider debugging");
         System.err.println("scl           permissions SecureClassLoader assigns");
         System.err.println("ts            timestamping");
         System.err.println();
--- a/src/share/classes/sun/security/x509/CertificateIssuerUniqueIdentity.java	Fri Sep 21 12:22:52 2012 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,177 +0,0 @@
-/*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.security.x509;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Enumeration;
-
-import sun.security.util.*;
-
-/**
- * This class defines the subject/issuer unique identity attribute
- * for the Certificate.
- *
- * @author Amit Kapoor
- * @author Hemma Prafullchandra
- * @see CertAttrSet
- */
-public class CertificateIssuerUniqueIdentity implements CertAttrSet<String> {
-    private UniqueIdentity      id;
-
-    /**
-     * Identifier for this attribute, to be used with the
-     * get, set, delete methods of Certificate, x509 type.
-     */
-    public static final String IDENT = "x509.info.issuerID";
-    /**
-     * Sub attributes name for this CertAttrSet.
-     */
-    public static final String NAME = "issuerID";
-    public static final String ID = "id";
-
-    /**
-     * Default constructor for the certificate attribute.
-     *
-     * @param key the UniqueIdentity
-     */
-    public CertificateIssuerUniqueIdentity(UniqueIdentity id) {
-        this.id = id;
-    }
-
-    /**
-     * Create the object, decoding the values from the passed DER stream.
-     *
-     * @param in the DerInputStream to read the UniqueIdentity from.
-     * @exception IOException on decoding errors.
-     */
-    public CertificateIssuerUniqueIdentity(DerInputStream in)
-    throws IOException {
-        id = new UniqueIdentity(in);
-    }
-
-    /**
-     * Create the object, decoding the values from the passed stream.
-     *
-     * @param in the InputStream to read the UniqueIdentity from.
-     * @exception IOException on decoding errors.
-     */
-    public CertificateIssuerUniqueIdentity(InputStream in)
-    throws IOException {
-        DerValue val = new DerValue(in);
-        id = new UniqueIdentity(val);
-    }
-
-    /**
-     * Create the object, decoding the values from the passed DER value.
-     *
-     * @param in the DerValue to read the UniqueIdentity from.
-     * @exception IOException on decoding errors.
-     */
-    public CertificateIssuerUniqueIdentity(DerValue val)
-    throws IOException {
-        id = new UniqueIdentity(val);
-    }
-
-    /**
-     * Return the identity as user readable string.
-     */
-    public String toString() {
-        if (id == null) return "";
-        return (id.toString());
-    }
-
-    /**
-     * Encode the identity in DER form to the stream.
-     *
-     * @param out the DerOutputStream to marshal the contents to.
-     * @exception IOException on errors.
-     */
-    public void encode(OutputStream out) throws IOException {
-        DerOutputStream tmp = new DerOutputStream();
-        id.encode(tmp,DerValue.createTag(DerValue.TAG_CONTEXT,false,(byte)1));
-
-        out.write(tmp.toByteArray());
-    }
-
-    /**
-     * Set the attribute value.
-     */
-    public void set(String name, Object obj) throws IOException {
-        if (!(obj instanceof UniqueIdentity)) {
-            throw new IOException("Attribute must be of type UniqueIdentity.");
-        }
-        if (name.equalsIgnoreCase(ID)) {
-            id = (UniqueIdentity)obj;
-        } else {
-            throw new IOException("Attribute name not recognized by " +
-                      "CertAttrSet: CertificateIssuerUniqueIdentity.");
-        }
-    }
-
-    /**
-     * Get the attribute value.
-     */
-    public UniqueIdentity get(String name) throws IOException {
-        if (name.equalsIgnoreCase(ID)) {
-            return (id);
-        } else {
-            throw new IOException("Attribute name not recognized by " +
-                      "CertAttrSet: CertificateIssuerUniqueIdentity.");
-        }
-    }
-
-    /**
-     * Delete the attribute value.
-     */
-    public void delete(String name) throws IOException {
-        if (name.equalsIgnoreCase(ID)) {
-            id = null;
-        } else {
-            throw new IOException("Attribute name not recognized by " +
-                      "CertAttrSet: CertificateIssuerUniqueIdentity.");
-        }
-    }
-
-    /**
-     * Return an enumeration of names of attributes existing within this
-     * attribute.
-     */
-    public Enumeration<String> getElements() {
-        AttributeNameEnumeration elements = new AttributeNameEnumeration();
-        elements.addElement(ID);
-
-        return (elements.elements());
-    }
-
-    /**
-     * Return the name of this attribute.
-     */
-    public String getName() {
-        return (NAME);
-    }
-}
--- a/src/share/classes/sun/security/x509/CertificateSubjectUniqueIdentity.java	Fri Sep 21 12:22:52 2012 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,176 +0,0 @@
-/*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-package sun.security.x509;
-
-import java.io.InputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.Enumeration;
-
-import sun.security.util.*;
-
-/**
- * This class defines the subject/issuer unique identity attribute
- * for the Certificate.
- *
- * @author Amit Kapoor
- * @author Hemma Prafullchandra
- * @see CertAttrSet
- */
-public class CertificateSubjectUniqueIdentity implements CertAttrSet<String> {
-    /**
-     * Identifier for this attribute, to be used with the
-     * get, set, delete methods of Certificate, x509 type.
-     */
-    public static final String IDENT = "x509.info.subjectID";
-    /**
-     * Sub attributes name for this CertAttrSet.
-     */
-    public static final String NAME = "subjectID";
-    public static final String ID = "id";
-
-    private UniqueIdentity      id;
-
-    /**
-     * Default constructor for the certificate attribute.
-     *
-     * @param key the UniqueIdentity
-     */
-    public CertificateSubjectUniqueIdentity(UniqueIdentity id) {
-        this.id = id;
-    }
-
-    /**
-     * Create the object, decoding the values from the passed DER stream.
-     *
-     * @param in the DerInputStream to read the UniqueIdentity from.
-     * @exception IOException on decoding errors.
-     */
-    public CertificateSubjectUniqueIdentity(DerInputStream in)
-    throws IOException {
-        id = new UniqueIdentity(in);
-    }
-
-    /**
-     * Create the object, decoding the values from the passed stream.
-     *
-     * @param in the InputStream to read the UniqueIdentity from.
-     * @exception IOException on decoding errors.
-     */
-    public CertificateSubjectUniqueIdentity(InputStream in)
-    throws IOException {
-        DerValue val = new DerValue(in);
-        id = new UniqueIdentity(val);
-    }
-
-    /**
-     * Create the object, decoding the values from the passed DER value.
-     *
-     * @param in the DerValue to read the UniqueIdentity from.
-     * @exception IOException on decoding errors.
-     */
-    public CertificateSubjectUniqueIdentity(DerValue val)
-    throws IOException {
-        id = new UniqueIdentity(val);
-    }
-
-    /**
-     * Return the identity as user readable string.
-     */
-    public String toString() {
-        if (id == null) return "";
-        return(id.toString());
-    }
-
-    /**
-     * Encode the identity in DER form to the stream.
-     *
-     * @param out the DerOutputStream to marshal the contents to.
-     * @exception IOException on errors.
-     */
-    public void encode(OutputStream out) throws IOException {
-        DerOutputStream tmp = new DerOutputStream();
-        id.encode(tmp,DerValue.createTag(DerValue.TAG_CONTEXT,false,(byte)2));
-
-        out.write(tmp.toByteArray());
-    }
-
-    /**
-     * Set the attribute value.
-     */
-    public void set(String name, Object obj) throws IOException {
-        if (!(obj instanceof UniqueIdentity)) {
-            throw new IOException("Attribute must be of type UniqueIdentity.");
-        }
-        if (name.equalsIgnoreCase(ID)) {
-            id = (UniqueIdentity)obj;
-        } else {
-            throw new IOException("Attribute name not recognized by " +
-                      "CertAttrSet: CertificateSubjectUniqueIdentity.");
-        }
-    }
-
-    /**
-     * Get the attribute value.
-     */
-    public UniqueIdentity get(String name) throws IOException {
-        if (name.equalsIgnoreCase(ID)) {
-            return(id);
-        } else {
-            throw new IOException("Attribute name not recognized by " +
-                      "CertAttrSet: CertificateSubjectUniqueIdentity.");
-        }
-    }
-
-    /**
-     * Delete the attribute value.
-     */
-    public void delete(String name) throws IOException {
-        if (name.equalsIgnoreCase(ID)) {
-            id = null;
-        } else {
-            throw new IOException("Attribute name not recognized by " +
-                      "CertAttrSet: CertificateSubjectUniqueIdentity.");
-        }
-    }
-
-    /**
-     * Return an enumeration of names of attributes existing within this
-     * attribute.
-     */
-    public Enumeration<String> getElements() {
-        AttributeNameEnumeration elements = new AttributeNameEnumeration();
-        elements.addElement(ID);
-
-        return (elements.elements());
-    }
-
-    /**
-     * Return the name of this attribute.
-     */
-    public String getName() {
-        return (NAME);
-    }
-}
--- a/src/share/classes/sun/security/x509/X509CertImpl.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/x509/X509CertImpl.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1070,8 +1070,7 @@
             return null;
         try {
             UniqueIdentity id = (UniqueIdentity)info.get(
-                                 CertificateIssuerUniqueIdentity.NAME
-                            + DOT + CertificateIssuerUniqueIdentity.ID);
+                                 X509CertInfo.ISSUER_ID);
             if (id == null)
                 return null;
             else
@@ -1091,8 +1090,7 @@
             return null;
         try {
             UniqueIdentity id = (UniqueIdentity)info.get(
-                                 CertificateSubjectUniqueIdentity.NAME
-                            + DOT + CertificateSubjectUniqueIdentity.ID);
+                                 X509CertInfo.SUBJECT_ID);
             if (id == null)
                 return null;
             else
--- a/src/share/classes/sun/security/x509/X509CertInfo.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/security/x509/X509CertInfo.java	Wed Sep 26 22:22:51 2012 -0700
@@ -75,8 +75,8 @@
     public static final String VALIDITY = CertificateValidity.NAME;
     public static final String SUBJECT = CertificateSubjectName.NAME;
     public static final String KEY = CertificateX509Key.NAME;
-    public static final String ISSUER_ID = CertificateIssuerUniqueIdentity.NAME;
-    public static final String SUBJECT_ID = CertificateSubjectUniqueIdentity.NAME;
+    public static final String ISSUER_ID = "issuerID";
+    public static final String SUBJECT_ID = "subjectID";
     public static final String EXTENSIONS = CertificateExtensions.NAME;
 
     // X509.v1 data
@@ -89,8 +89,8 @@
     protected CertificateX509Key        pubKey = null;
 
     // X509.v2 & v3 extensions
-    protected CertificateIssuerUniqueIdentity   issuerUniqueId = null;
-    protected CertificateSubjectUniqueIdentity  subjectUniqueId = null;
+    protected UniqueIdentity   issuerUniqueId = null;
+    protected UniqueIdentity  subjectUniqueId = null;
 
     // X509.v3 extensions
     protected CertificateExtensions     extensions = null;
@@ -431,19 +431,11 @@
             break;
 
         case ATTR_ISSUER_ID:
-            if (suffix == null) {
-                setIssuerUniqueId(val);
-            } else {
-                issuerUniqueId.set(suffix, val);
-            }
+            setIssuerUniqueId(val);
             break;
 
         case ATTR_SUBJECT_ID:
-            if (suffix == null) {
-                setSubjectUniqueId(val);
-            } else {
-                subjectUniqueId.set(suffix, val);
-            }
+            setSubjectUniqueId(val);
             break;
 
         case ATTR_EXTENSIONS:
@@ -529,18 +521,10 @@
             }
             break;
         case (ATTR_ISSUER_ID):
-            if (suffix == null) {
-                issuerUniqueId = null;
-            } else {
-                issuerUniqueId.delete(suffix);
-            }
+            issuerUniqueId = null;
             break;
         case (ATTR_SUBJECT_ID):
-            if (suffix == null) {
-                subjectUniqueId = null;
-            } else {
-                subjectUniqueId.delete(suffix);
-            }
+            subjectUniqueId = null;
             break;
         case (ATTR_EXTENSIONS):
             if (suffix == null) {
@@ -626,23 +610,9 @@
                 return(serialNum.get(suffix));
             }
         case (ATTR_ISSUER_ID):
-            if (suffix == null) {
-                return(issuerUniqueId);
-            } else {
-                if (issuerUniqueId == null)
-                    return null;
-                else
-                    return(issuerUniqueId.get(suffix));
-            }
+            return(issuerUniqueId);
         case (ATTR_SUBJECT_ID):
-            if (suffix == null) {
-                return(subjectUniqueId);
-            } else {
-                if (subjectUniqueId == null)
-                    return null;
-                else
-                    return(subjectUniqueId.get(suffix));
-            }
+            return(subjectUniqueId);
         }
         return null;
     }
@@ -711,7 +681,7 @@
         // Get the issuerUniqueId if present
         tmp = in.getDerValue();
         if (tmp.isContextSpecific((byte)1)) {
-            issuerUniqueId = new CertificateIssuerUniqueIdentity(tmp);
+            issuerUniqueId = new UniqueIdentity(tmp);
             if (in.available() == 0)
                 return;
             tmp = in.getDerValue();
@@ -719,7 +689,7 @@
 
         // Get the subjectUniqueId if present.
         if (tmp.isContextSpecific((byte)2)) {
-            subjectUniqueId = new CertificateSubjectUniqueIdentity(tmp);
+            subjectUniqueId = new UniqueIdentity(tmp);
             if (in.available() == 0)
                 return;
             tmp = in.getDerValue();
@@ -814,10 +784,12 @@
 
         // Encode issuerUniqueId & subjectUniqueId.
         if (issuerUniqueId != null) {
-            issuerUniqueId.encode(tmp);
+            issuerUniqueId.encode(tmp, DerValue.createTag(DerValue.TAG_CONTEXT,
+                                                          false,(byte)1));
         }
         if (subjectUniqueId != null) {
-            subjectUniqueId.encode(tmp);
+            subjectUniqueId.encode(tmp, DerValue.createTag(DerValue.TAG_CONTEXT,
+                                                           false,(byte)2));
         }
 
         // Write all the extensions.
@@ -946,11 +918,11 @@
         if (version.compare(CertificateVersion.V2) < 0) {
             throw new CertificateException("Invalid version");
         }
-        if (!(val instanceof CertificateIssuerUniqueIdentity)) {
+        if (!(val instanceof UniqueIdentity)) {
             throw new CertificateException(
                              "IssuerUniqueId class type invalid.");
         }
-        issuerUniqueId = (CertificateIssuerUniqueIdentity)val;
+        issuerUniqueId = (UniqueIdentity)val;
     }
 
     /**
@@ -963,11 +935,11 @@
         if (version.compare(CertificateVersion.V2) < 0) {
             throw new CertificateException("Invalid version");
         }
-        if (!(val instanceof CertificateSubjectUniqueIdentity)) {
+        if (!(val instanceof UniqueIdentity)) {
             throw new CertificateException(
                              "SubjectUniqueId class type invalid.");
         }
-        subjectUniqueId = (CertificateSubjectUniqueIdentity)val;
+        subjectUniqueId = (UniqueIdentity)val;
     }
 
     /**
--- a/src/share/classes/sun/util/PreHashedMap.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/share/classes/sun/util/PreHashedMap.java	Wed Sep 26 22:22:51 2012 -0700
@@ -126,7 +126,7 @@
      */
     protected abstract void init(Object[] ht);
 
-    // @SuppressWarnings("unchecked")
+    @SuppressWarnings("unchecked")
     private V toV(Object x) {
         return (V)x;
     }
@@ -259,8 +259,7 @@
                                     return true;
                                 if (!(ob instanceof Map.Entry))
                                     return false;
-                                Map.Entry<String,V> that
-                                    = (Map.Entry<String,V>)ob;
+                                Map.Entry<?,?> that = (Map.Entry<?,?>)ob;
                                 return ((this.getKey() == null
                                          ? that.getKey() == null
                                          : this.getKey()
--- a/src/solaris/classes/sun/nio/ch/DefaultAsynchronousChannelProvider.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/solaris/classes/sun/nio/ch/DefaultAsynchronousChannelProvider.java	Wed Sep 26 22:22:51 2012 -0700
@@ -40,6 +40,22 @@
      */
     private DefaultAsynchronousChannelProvider() { }
 
+    @SuppressWarnings("unchecked")
+    private static AsynchronousChannelProvider createProvider(String cn) {
+        Class<AsynchronousChannelProvider> c;
+        try {
+            c = (Class<AsynchronousChannelProvider>)Class.forName(cn);
+        } catch (ClassNotFoundException x) {
+            throw new AssertionError(x);
+        }
+        try {
+            return c.newInstance();
+        } catch (IllegalAccessException | InstantiationException x) {
+            throw new AssertionError(x);
+        }
+
+    }
+
     /**
      * Returns the default AsynchronousChannelProvider.
      */
@@ -47,12 +63,11 @@
         String osname = AccessController
             .doPrivileged(new GetPropertyAction("os.name"));
         if (osname.equals("SunOS"))
-            return new SolarisAsynchronousChannelProvider();
+            return createProvider("sun.nio.ch.SolarisAsynchronousChannelProvider");
         if (osname.equals("Linux"))
-            return new LinuxAsynchronousChannelProvider();
+            return createProvider("sun.nio.ch.LinuxAsynchronousChannelProvider");
         if (osname.contains("OS X"))
-            return new BsdAsynchronousChannelProvider();
+            return createProvider("sun.nio.ch.BsdAsynchronousChannelProvider");
         throw new InternalError("platform not recognized");
     }
-
 }
--- a/src/solaris/classes/sun/nio/ch/DefaultSelectorProvider.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/solaris/classes/sun/nio/ch/DefaultSelectorProvider.java	Wed Sep 26 22:22:51 2012 -0700
@@ -27,7 +27,6 @@
 
 import java.nio.channels.spi.SelectorProvider;
 import java.security.AccessController;
-import java.security.PrivilegedAction;
 import sun.security.action.GetPropertyAction;
 
 /**
@@ -41,34 +40,32 @@
      */
     private DefaultSelectorProvider() { }
 
+    @SuppressWarnings("unchecked")
+    private static SelectorProvider createProvider(String cn) {
+        Class<SelectorProvider> c;
+        try {
+            c = (Class<SelectorProvider>)Class.forName(cn);
+        } catch (ClassNotFoundException x) {
+            throw new AssertionError(x);
+        }
+        try {
+            return c.newInstance();
+        } catch (IllegalAccessException | InstantiationException x) {
+            throw new AssertionError(x);
+        }
+
+    }
+
     /**
      * Returns the default SelectorProvider.
      */
     public static SelectorProvider create() {
-        String osname = AccessController.doPrivileged(
-            new GetPropertyAction("os.name"));
-        if ("SunOS".equals(osname)) {
-            return new sun.nio.ch.DevPollSelectorProvider();
-        }
-
-        // use EPollSelectorProvider for Linux kernels >= 2.6
-        if ("Linux".equals(osname)) {
-            String osversion = AccessController.doPrivileged(
-                new GetPropertyAction("os.version"));
-            String[] vers = osversion.split("\\.", 0);
-            if (vers.length >= 2) {
-                try {
-                    int major = Integer.parseInt(vers[0]);
-                    int minor = Integer.parseInt(vers[1]);
-                    if (major > 2 || (major == 2 && minor >= 6)) {
-                        return new sun.nio.ch.EPollSelectorProvider();
-                    }
-                } catch (NumberFormatException x) {
-                    // format not recognized
-                }
-            }
-        }
-
+        String osname = AccessController
+            .doPrivileged(new GetPropertyAction("os.name"));
+        if (osname.equals("SunOS"))
+            return createProvider("sun.nio.ch.DevPollSelectorProvider");
+        if (osname.equals("Linux"))
+            return createProvider("sun.nio.ch.EPollSelectorProvider");
         return new sun.nio.ch.PollSelectorProvider();
     }
 
--- a/src/solaris/classes/sun/nio/fs/DefaultFileSystemProvider.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/solaris/classes/sun/nio/fs/DefaultFileSystemProvider.java	Wed Sep 26 22:22:51 2012 -0700
@@ -27,7 +27,6 @@
 
 import java.nio.file.spi.FileSystemProvider;
 import java.security.AccessController;
-import java.security.PrivilegedAction;
 import sun.security.action.GetPropertyAction;
 
 /**
@@ -38,24 +37,18 @@
     private DefaultFileSystemProvider() { }
 
     @SuppressWarnings("unchecked")
-    private static FileSystemProvider createProvider(final String cn) {
-        return AccessController
-            .doPrivileged(new PrivilegedAction<FileSystemProvider>() {
-                public FileSystemProvider run() {
-                    Class<FileSystemProvider> c;
-                    try {
-                        c = (Class<FileSystemProvider>)Class.forName(cn, true, null);
-                    } catch (ClassNotFoundException x) {
-                        throw new AssertionError(x);
-                    }
-                    try {
-                        return c.newInstance();
-                    } catch (IllegalAccessException x) {
-                        throw new AssertionError(x);
-                    } catch (InstantiationException x) {
-                        throw new AssertionError(x);
-                    }
-            }});
+    private static FileSystemProvider createProvider(String cn) {
+        Class<FileSystemProvider> c;
+        try {
+            c = (Class<FileSystemProvider>)Class.forName(cn);
+        } catch (ClassNotFoundException x) {
+            throw new AssertionError(x);
+        }
+        try {
+            return c.newInstance();
+        } catch (IllegalAccessException | InstantiationException x) {
+            throw new AssertionError(x);
+        }
     }
 
     /**
@@ -68,7 +61,7 @@
             return createProvider("sun.nio.fs.SolarisFileSystemProvider");
         if (osname.equals("Linux"))
             return createProvider("sun.nio.fs.LinuxFileSystemProvider");
-        if (osname.equals("Darwin") || osname.contains("OS X"))
+        if (osname.contains("OS X"))
             return createProvider("sun.nio.fs.MacOSXFileSystemProvider");
         throw new AssertionError("Platform not recognized");
     }
--- a/src/windows/classes/sun/java2d/ScreenUpdateManager.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/windows/classes/sun/java2d/ScreenUpdateManager.java	Wed Sep 26 22:22:51 2012 -0700
@@ -110,6 +110,11 @@
     public SurfaceData getReplacementScreenSurface(WComponentPeer peer,
                                                    SurfaceData oldsd)
     {
+        SurfaceData surfaceData = peer.getSurfaceData();
+        if (surfaceData.isValid()) {
+            return surfaceData;
+        }
+        peer.replaceSurfaceData();
         return peer.getSurfaceData();
     }
 
--- a/src/windows/native/sun/windows/awt_DesktopProperties.cpp	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/windows/native/sun/windows/awt_DesktopProperties.cpp	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -70,6 +70,7 @@
     GetNonClientParameters();
     GetIconParameters();
     GetColorParameters();
+    GetCaretParameters();
     GetOtherParameters();
     GetSoundEvents();
     GetSystemProperties();
@@ -636,6 +637,10 @@
     SetSoundProperty(TEXT("win.sound.start"), TEXT("SystemStart"));
 }
 
+void AwtDesktopProperties::GetCaretParameters() {
+    SetIntegerProperty(TEXT("win.caret.width"), GetIntegerParameter(SPI_GETCARETWIDTH));
+}
+
 BOOL AwtDesktopProperties::GetBooleanParameter(UINT spi) {
     BOOL        flag;
     SystemParametersInfo(spi, 0, &flag, 0);
--- a/src/windows/native/sun/windows/awt_DesktopProperties.h	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/windows/native/sun/windows/awt_DesktopProperties.h	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -64,6 +64,7 @@
         void GetColorParameters();
         void GetOtherParameters();
         void GetSoundEvents();
+        void GetCaretParameters();
 
         static BOOL GetBooleanParameter(UINT spi);
         static UINT GetIntegerParameter(UINT spi);
--- a/src/windows/native/sun/windows/awt_TextField.cpp	Fri Sep 21 12:22:52 2012 -0700
+++ b/src/windows/native/sun/windows/awt_TextField.cpp	Wed Sep 26 22:22:51 2012 -0700
@@ -75,6 +75,7 @@
 AwtTextField::HandleEvent(MSG *msg, BOOL synthetic)
 {
     MsgRouting returnVal;
+    BOOL systemBeeperEnabled = FALSE;
     /*
      * RichEdit 1.0 control starts internal message loop if the
      * left mouse button is pressed while the cursor is not over
@@ -217,7 +218,34 @@
         }
         delete msg;
         return mrConsume;
+    } else if (msg->message == WM_KEYDOWN) {
+        UINT virtualKey = (UINT) msg->wParam;
+
+        switch(virtualKey){
+          case VK_RETURN:
+          case VK_UP:
+          case VK_DOWN:
+          case VK_LEFT:
+          case VK_RIGHT:
+          case VK_DELETE:
+          case VK_BACK:
+              SystemParametersInfo(SPI_GETBEEP, 0, &systemBeeperEnabled, 0);
+              if(systemBeeperEnabled){
+                  // disable system beeper for the RICHEDIT control to be compatible
+                  // with the EDIT control behaviour
+                  SystemParametersInfo(SPI_SETBEEP, 0, NULL, 0);
+              }
+              break;
+          }
+    } else if (msg->message == WM_SETTINGCHANGE) {
+        if (msg->wParam == SPI_SETBEEP) {
+            SystemParametersInfo(SPI_GETBEEP, 0, &systemBeeperEnabled, 0);
+            if(systemBeeperEnabled){
+                SystemParametersInfo(SPI_SETBEEP, 1, NULL, 0);
+            }
+        }
     }
+
     /*
      * Store the 'synthetic' parameter so that the WM_PASTE security check
      * happens only for synthetic events.
@@ -226,6 +254,10 @@
     returnVal = AwtComponent::HandleEvent(msg, synthetic);
     m_synthetic = FALSE;
 
+    if(systemBeeperEnabled){
+        SystemParametersInfo(SPI_SETBEEP, 1, NULL, 0);
+    }
+
     return returnVal;
 }
 
--- a/test/ProblemList.txt	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/ProblemList.txt	Wed Sep 26 22:22:51 2012 -0700
@@ -134,6 +134,15 @@
 # 7148492
 java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java	generic-all
 
+# 7196801
+java/lang/management/MemoryMXBean/LowMemoryTest2.sh		generic-all
+
+# Exclude until the fix for 7195557 propagates widely.
+java/lang/management/MemoryMXBean/CollectionUsageThresholdParallelGC.sh generic-all
+java/lang/management/MemoryMXBean/CollectionUsageThresholdSerialGC.sh generic-all
+java/lang/management/MemoryMXBean/MemoryTest.java		generic-all
+java/lang/management/MemoryMXBean/MemoryTestAllGC.sh		generic-all
+
 ############################################################################
 
 # jdk_management
@@ -147,6 +156,9 @@
 # 7158614, locks up Windows machines at least
 sun/management/jmxremote/startstop/JMXStartStopTest.sh		windows-all
 
+# 7120365
+javax/management/remote/mandatory/notif/DiffHBTest.java 	generic-all
+
 ############################################################################
 
 # jdk_math
@@ -216,11 +228,6 @@
 sun/net/www/protocol/http/B6299712.java                         macosx-all
 java/net/CookieHandler/CookieManagerTest.java                   macosx-all
 
-# 7164518
-sun/security/krb5/auto/Unreachable.java                         macosx-all
-
-# JPRT needs to set 127.0.0.1 in proxy bypass list
-java/net/URLClassLoader/closetest/CloseTest.java                macosx-all
 ############################################################################
 
 # jdk_io
@@ -251,9 +258,6 @@
 # 7132677
 java/nio/channels/Selector/OutOfBand.java                       macosx-all
 
-# 7142919
-java/nio/channels/AsyncCloseAndInterrupt.java			solaris-all
-
 ############################################################################
 
 # jdk_rmi
@@ -277,6 +281,9 @@
 
 # jdk_security
 
+# 7164518: no PortUnreachableException on Mac
+sun/security/krb5/auto/Unreachable.java                         macosx-all
+
 # 7193792
 sun/security/pkcs11/ec/TestECDSA.java				solaris-all
 sun/security/pkcs11/ec/TestECDSA.java				linux-all
@@ -284,47 +291,17 @@
 # 7193793
 sun/security/pkcs11/ec/TestECDH.java				linux-all
 
+# 7198198: the test also fails on SuSE Linux
+sun/security/pkcs11/ec/ReadCertificates.java                    linux-all
+
 # 7147060
 com/sun/org/apache/xml/internal/security/transforms/ClassLoaderTest.java	generic-all
 
-# Failing on Solaris i586, 3/9/2010, not a -samevm issue (jdk_security3)
-sun/security/pkcs11/Secmod/AddPrivateKey.java                   solaris-i586
-sun/security/pkcs11/ec/ReadCertificates.java                    generic-all
-sun/security/pkcs11/ec/ReadPKCS12.java                          generic-all
-sun/security/pkcs11/ec/TestCurves.java                          solaris-i586
-#sun/security/pkcs11/ec/TestECGenSpec.java                      solaris-i586
-#sun/security/pkcs11/ec/TestKeyFactory.java                     solaris-i586
-sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java            generic-all
-
-# Fails on Fedora 9/Ubuntu 10.04 64bit, PKCS11Exception: CKR_DEVICE_ERROR
-sun/security/pkcs11/KeyAgreement/TestDH.java                    generic-all
-
-# Run too slow on Solaris 10 sparc
-sun/security/ssl/com/sun/net/ssl/internal/ssl/InputRecord/SSLSocketTimeoutNulls.java solaris-sparc
-sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/ClientTimeout.java solaris-sparc
-sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/ServerTimeout.java solaris-sparc
-sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/ReadTimeout.java solaris-sparc
-sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/NotifyHandshakeTest.sh solaris-sparc
-
-# Solaris 10 sparc, passed/failed confusion? java.security.ProviderException: update() failed
-sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/AsyncSSLSocketClose.java generic-all
-
-# Othervm, sparc, NoRouteToHostException: Cannot assign requested address
-sun/security/ssl/javax/net/ssl/NewAPIs/SessionCacheSizeTests.java generic-all
-
-# Times out on windows X64, othervm mode
-#    Solaris sparc and sparcv9 -server, timeout
-sun/security/ssl/javax/net/ssl/NewAPIs/SessionTimeOutTests.java generic-all
-
-# Various failures on Linux Fedora 9 X64, othervm mode
-sun/security/ssl/javax/net/ssl/NewAPIs/SSLEngine/TestAllSuites.java generic-all
-sun/security/ssl/sanity/ciphersuites/CheckCipherSuites.java     generic-all
-
-# Various failures on Linux Fedora 9 X64, othervm mode
-sun/security/ssl/sanity/interop/ClientJSSEServerJSSE.java       generic-all
-
-# 7079203 sun/security/tools/keytool/printssl.sh fails on solaris with timeout
-sun/security/tools/keytool/printssl.sh                          solaris-all
+# 6988842: 4 tests failing on Solaris 5.10
+sun/security/pkcs11/Secmod/AddPrivateKey.java                   solaris-all
+sun/security/pkcs11/ec/ReadCertificates.java                    solaris-all
+sun/security/pkcs11/ec/ReadPKCS12.java                          solaris-all
+sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java            solaris-all
 
 # 7041639, Solaris DSA keypair generation bug (Note: jdk_util also affected)
 java/security/KeyPairGenerator/SolarisShortDSA.java             solaris-all
@@ -348,6 +325,8 @@
 
 # jdk_text
 
+# 7196199
+java/text/Bidi/Bug6665028.java                                  generic-all
 ############################################################################
 
 # jdk_tools
--- a/test/com/sun/crypto/provider/Cipher/DES/PaddingTest.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/com/sun/crypto/provider/Cipher/DES/PaddingTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -195,7 +195,7 @@
 
     private static void diff(String fname1, String fname2) throws Exception {
         if (!Arrays.equals(Files.readAllBytes(Paths.get(fname1)),
-                Files.readAllBytes(Paths.get(fname1)))) {
+                Files.readAllBytes(Paths.get(fname2)))) {
             throw new Exception(
                     "files " + fname1 + " and " + fname2 + " differ");
         }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/EventQueue/PostEventOrderingTest/PostEventOrderingTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test PostEventOrderingTest.java
+ * @bug 4171596 6699589
+ * @summary Checks that the posting of events between the PostEventQueue
+ * @summary and the EventQueue maintains proper ordering.
+ * @run main PostEventOrderingTest
+ * @author fredx
+ */
+
+import java.awt.*;
+import java.awt.event.*;
+import sun.awt.AppContext;
+import sun.awt.SunToolkit;
+
+public class PostEventOrderingTest {
+    static boolean testPassed = true;
+
+    public static void main(String[] args) throws Throwable {
+        EventQueue q = Toolkit.getDefaultToolkit().getSystemEventQueue();
+        for (int i = 0; i < 100; i++) {
+            for (int j = 0; j < 100; j++) {
+                q.postEvent(new PostActionEvent());
+                for (int k = 0; k < 10; k++) {
+                    SunToolkit.postEvent(AppContext.getAppContext(), new PostActionEvent());
+                }
+            }
+            for (int k = 0; k < 100; k++) {
+                SunToolkit.postEvent(AppContext.getAppContext(), new PostActionEvent());
+            }
+        }
+
+        for (;;) {
+            Thread.currentThread().sleep(100);
+            if (q.peekEvent() == null) {
+                Thread.currentThread().sleep(100);
+                if (q.peekEvent() == null)
+                    break;
+            }
+        }
+
+        if (!testPassed) {
+            throw new Exception("PostEventOrderingTest FAILED -- events dispatched out of order.");
+        } else {
+            System.out.println("PostEventOrderingTest passed!");
+        }
+    }
+}
+
+class PostActionEvent extends ActionEvent implements ActiveEvent {
+    static int counter = 0;
+    static int mostRecent = -1;
+
+    int myval;
+
+    public PostActionEvent() {
+        super("", ACTION_PERFORMED, "" + counter);
+        myval = counter++;
+    }
+
+    public void dispatch() {
+        //System.out.println("myval = "+myval+", mostRecent = "+mostRecent+", diff = "+(myval-mostRecent)+".");
+        if ((myval - mostRecent) != 1)
+            PostEventOrderingTest.testPassed = false;
+        mostRecent = myval;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/JAWT/JAWT.sh	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,173 @@
+#!/bin/sh
+
+# Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+
+# @test JAWT.sh
+# @bug 7190587
+# @summary Tests Java AWT native interface library
+# @author kshefov
+# @run shell JAWT.sh
+
+# NB: To run on Windows with MKS and Visual Studio compiler
+# add the following options to jtreg: -e INCLUDE="%INCLUDE%;." -e LIB="%LIB%;."
+
+if [ "${TESTSRC}" = "" ]
+then TESTSRC=.
+fi
+
+if [ "${TESTJAVA}" = "" ]
+then
+  PARENT=`dirname \`which java\``
+  TESTJAVA=`dirname ${PARENT}`
+  echo "TESTJAVA not set, selecting " ${TESTJAVA}
+  echo "If this is incorrect, try setting the variable manually."
+fi
+
+# set platform-dependent variables
+OS=`uname -s`
+case "$OS" in
+  Linux )
+    NULL=/dev/null
+    PS=":"
+    FS="/"
+    ${TESTJAVA}${FS}bin${FS}java -version 2>&1 | grep '64-Bit' > $NULL
+    if [ $? -eq '0' ]
+    then
+        ARCH="amd64"
+    else
+        ARCH="i386"
+    fi
+    SYST="linux"
+    MAKEFILE="Makefile.unix"
+    CC="gcc"
+	MAKE="make"
+	LD_LIBRARY_PATH="."
+    ;;
+  SunOS )
+    NULL=/dev/null
+    PS=":"
+    FS="/"
+    if [ `uname -p | grep -c 'sparc'` -gt '0' ]
+    then
+        ARCH="sparc"
+    else
+        ARCH="i386"
+    fi
+    SYST="solaris"
+    MAKEFILE="Makefile.unix"
+    CC="gcc"
+	MAKE="make"
+	LD_LIBRARY_PATH="."
+    ;;
+  Windows* )
+    NULL=null
+    PS=";"
+    FS="\\"
+    MAKEFILE="Makefile.win"
+    CC="cl"
+	MAKE="nmake"
+	${TESTJAVA}${FS}bin${FS}java -d64 -version 2>&1 | grep '64-Bit' > $NULL
+    if [ "$?" -eq '0' ]
+    then
+        ARCH="amd64"
+    else
+        ARCH="i386"
+    fi
+	SYST="windows"
+    ;;
+  CYGWIN* )
+    NULL=/dev/null
+    PS=":"
+    FS="/"
+    MAKEFILE="Makefile.cygwin"
+    CC="gcc"
+	${TESTJAVA}${FS}bin${FS}java -d64 -version 2>&1 | grep '64-Bit' > $NULL
+    if [ "$?" -eq '0' ]
+    then
+        ARCH="amd64"
+    else
+        ARCH="i386"
+    fi
+	SYST="cygwin"	
+	MAKE="make"
+    ;;
+  Darwin )
+    echo "Test passed. This test is not for MacOS."
+    exit 0;
+    ;;
+  * )
+    echo "Unrecognized system!"
+    exit 1;
+    ;;
+esac
+
+# Skip unsupported platforms
+case `uname -m` in
+    arm* | ppc* )
+      echo "Test passed. Not supported on current architecture."
+      exit 0
+      ;;
+esac
+
+echo "OS-ARCH is" ${SYST}-${ARCH}
+${TESTJAVA}${FS}jre${FS}bin${FS}java -fullversion 2>&1
+
+which ${MAKE} >${NULL} 2>&1
+if [ "$?" -ne '0' ]
+then
+    echo "No make found. Test passed."
+    exit 0
+fi
+
+which ${CC} >${NULL} 2>&1
+if [ "$?" -ne '0' ]
+then
+    echo "No C compiler found. Test passed."
+    exit 0
+fi
+case "$OS" in
+    SunOS )
+      ${CC} -v >${NULL} 2>&1
+      if [ "$?" -ne '0' ]
+      then
+          echo "No C compiler found. Test passed."
+          exit 0
+      fi
+esac
+
+cp ${TESTSRC}${FS}${MAKEFILE} .
+
+JAVA=${TESTJAVA}${FS}jre${FS}bin${FS}java
+JAVAC=${TESTJAVA}${FS}bin${FS}javac
+JAVAH=${TESTJAVA}${FS}bin${FS}javah
+
+export CC SYST ARCH LD_LIBRARY_PATH
+
+${JAVAC} -d . ${TESTSRC}${FS}MyCanvas.java
+${JAVAH} -jni -classpath . -d . MyCanvas
+${MAKE} -f ${MAKEFILE}
+${JAVA} -classpath . MyCanvas
+
+exit $?
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/JAWT/Makefile.cygwin	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,49 @@
+# Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  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.
+
+CFLAGS =	
+OBJS =		myfile.o
+HEADERS =	MyCanvas.h
+CLASSES =	MyCanvas.class
+
+JAVA =		$(TESTJAVA)/bin/java -classpath .
+JAVAC =		$(TESTJAVA)/bin/javac
+JAVAH =		$(TESTJAVA)/bin/javah
+DEL =		rm -rf
+LINK =		$(CC)
+
+INCLUDES =	-I $(TESTJAVA)/include/win32 -I $(TESTJAVA)/include -I .
+
+LIBS =		$(TESTJAVA)/lib/jawt.lib -lgdi32
+
+all:		$(CLASSES) mylib.dll
+
+mylib.dll: $(HEADERS) $(OBJS) 
+	$(LINK) -shared -o mylib.dll $(OBJS) $(LIBS) 
+
+myfile.o:
+	$(CC) $(CFLAGS)  $(INCLUDES) -c $(TESTSRC)/myfile.cpp
+
+clean:
+	$(DEL) mylib.* *.h *.class *.o
+ 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/JAWT/Makefile.unix	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,48 @@
+# Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  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.
+
+CFLAGS =	-fPIC -O
+OBJS =		myfile.o
+HEADERS =	MyCanvas.h
+CLASSES =	MyCanvas.class
+
+ENV =		/usr/bin/env
+JAVA =		$(TESTJAVA)/bin/java -classpath .
+JAVAC =		$(TESTJAVA)/bin/javac
+JAVAH =		$(TESTJAVA)/bin/javah
+LINK =		ld
+
+J_INC =		$(TESTJAVA)/include
+INCLUDES =	-I$(J_INC) -I$(J_INC)/$(SYST) -I.
+LIBS =		-L$(TESTJAVA)/jre/lib/$(ARCH) -ljawt -lX11
+
+all:		$(CLASSES) libmylib.so
+
+libmylib.so: $(HEADERS) $(OBJS) 
+	$(LINK) -G -o libmylib.so $(OBJS) $(LIBS)
+
+myfile.o:	$(TESTSRC)/myfile.c
+	$(CC)  $(CFLAGS) $(INCLUDES) -c $(TESTSRC)/myfile.c
+
+clean:
+	rm -rf libmylib.so $(HEADERS) $(CLASSES) $(OBJS)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/JAWT/Makefile.win	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,47 @@
+# Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  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.
+
+CFLAGS =	-nologo
+OBJS =		myfile.obj
+HEADERS =	MyCanvas.h
+CLASSES =	MyCanvas.class
+
+DEL =		del /Q
+LINK =		link
+
+INCLUDES =	-I$(TESTJAVA)\include\win32 -I$(TESTJAVA)\include
+
+LIBS =		gdi32.lib user32.lib $(TESTJAVA)\lib\jawt.lib
+
+all:		$(CLASSES) mylib.dll
+
+mylib.dll: $(HEADERS) $(OBJS) 
+	$(LINK) -nologo -dll -out:mylib.dll $(OBJS) $(LIBS)
+
+myfile.obj: $(TESTSRC)\myfile.cpp
+	$(CC) $(CFLAGS) $(INCLUDES) -c $(TESTSRC)\myfile.cpp
+
+clean:
+	$(DEL) mylib.* 
+	$(DEL) $(HEADERS) $(CLASSES)
+	$(DEL) *.obj
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/JAWT/MyCanvas.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,72 @@
+/**
+ * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.awt.event.*;
+
+public class MyCanvas extends Canvas {
+
+    static {
+        try {
+            System.loadLibrary("mylib");
+        } catch (Throwable t) {
+            System.out.println("Test failed!!");
+            t.printStackTrace();
+            System.exit(1);
+        }
+    }
+
+    public native void paint(Graphics g);
+
+    public static void main(String[] args) {
+        try {
+            Robot robot = new Robot();
+            Frame f = new Frame();
+            f.setBounds(0, 0, 100, 100);
+            f.add(new MyCanvas());
+            f.addWindowListener(new WindowAdapter() {
+                public void windowClosing(WindowEvent ev) {
+                    System.exit(0);
+                }
+            });
+            f.setVisible(true);
+            robot.delay(5000);
+            Color col1 = new Color(0, 0, 0);
+            Color col2 = robot.getPixelColor(f.getX()+50, f.getY()+50);
+            if (col1.equals(col2)) {
+                System.out.println("Test passed!");
+            } else {
+                throw new RuntimeException("Color of JAWT canvas is wrong or " +
+                        "it was not rendered. " + "Check that other windows " +
+                        "do not block the test frame.");
+            }
+            System.exit(0);
+        } catch (Throwable t) {
+            System.out.println("Test failed!");
+            t.printStackTrace();
+            System.exit(1);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/JAWT/myfile.c	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include "MyCanvas.h"
+#include "jawt_md.h"
+
+/*
+ * Class:     MyCanvas
+ * Method:    paint
+ * Signature: (Ljava/awt/Graphics;)V
+ */
+JNIEXPORT void JNICALL Java_MyCanvas_paint
+(JNIEnv* env, jobject canvas, jobject graphics)
+{
+    JAWT awt;
+    JAWT_DrawingSurface* ds;
+    JAWT_DrawingSurfaceInfo* dsi;
+    JAWT_X11DrawingSurfaceInfo* dsi_x11;
+    jboolean result;
+    jint lock;
+    GC gc;
+    jobject ref;
+
+    /* Get the AWT */
+    awt.version = JAWT_VERSION_1_4;
+    if (JAWT_GetAWT(env, &awt) == JNI_FALSE) {
+        printf("AWT Not found\n");
+        return;
+    }
+
+    /* Lock the AWT */
+    awt.Lock(env);
+
+    /* Unlock the AWT */
+    awt.Unlock(env);
+
+    /* Get the drawing surface */
+    ds = awt.GetDrawingSurface(env, canvas);
+    if (ds == NULL) {
+        printf("NULL drawing surface\n");
+        return;
+    }
+
+    /* Lock the drawing surface */
+    lock = ds->Lock(ds);
+    printf("Lock value %d\n", (int)lock);
+    if((lock & JAWT_LOCK_ERROR) != 0) {
+        printf("Error locking surface\n");
+        awt.FreeDrawingSurface(ds);
+        return;
+    }
+
+    /* Get the drawing surface info */
+    dsi = ds->GetDrawingSurfaceInfo(ds);
+    if (dsi == NULL) {
+        printf("Error getting surface info\n");
+        ds->Unlock(ds);
+        awt.FreeDrawingSurface(ds);
+        return;
+    }
+
+    /* Get the platform-specific drawing info */
+    dsi_x11 = (JAWT_X11DrawingSurfaceInfo*)dsi->platformInfo;
+
+    /* Now paint */
+    gc = XCreateGC(dsi_x11->display, dsi_x11->drawable, 0, 0);
+    XSetForeground(dsi_x11->display, gc, 0);
+    XFillRectangle(dsi_x11->display, dsi_x11->drawable, gc,
+                   5, 5, 90, 90);
+    XFreeGC(dsi_x11->display, gc);
+    ref = awt.GetComponent(env, (void*)(dsi_x11->drawable));
+    if (!(*env)->IsSameObject(env, ref, canvas)) {
+        printf("Error! Different objects!\n");
+    }
+
+    /* Free the drawing surface info */
+    ds->FreeDrawingSurfaceInfo(dsi);
+
+    /* Unlock the drawing surface */
+    ds->Unlock(ds);
+
+    /* Free the drawing surface */
+    awt.FreeDrawingSurface(ds);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/JAWT/myfile.cpp	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include <windows.h>
+#include "MyCanvas.h"
+#include "jawt_md.h"
+
+/*
+ * Class:     MyCanvas
+ * Method:    paint
+ * Signature: (Ljava/awt/Graphics;)V
+ */
+
+extern "C" {
+
+JNIEXPORT void JNICALL Java_MyCanvas_paint
+(JNIEnv* env, jobject canvas, jobject graphics)
+{
+    /* Get the AWT */
+    JAWT awt;
+    awt.version = JAWT_VERSION_1_4;
+    if (JAWT_GetAWT(env, &awt) == JNI_FALSE) {
+        printf("AWT Not found\n");
+        return;
+    }
+
+    /* Lock the AWT */
+    awt.Lock(env);
+
+    /* Unlock the AWT */
+    awt.Unlock(env);
+
+    /* Get the drawing surface */
+    JAWT_DrawingSurface* ds = awt.GetDrawingSurface(env, canvas);
+    if (ds == NULL) {
+        printf("NULL drawing surface\n");
+        return;
+    }
+
+    /* Lock the drawing surface */
+    jint lock = ds->Lock(ds);
+    printf("Lock value %d\n", (int)lock);
+    if((lock & JAWT_LOCK_ERROR) != 0) {
+        printf("Error locking surface\n");
+        return;
+    }
+
+    /* Get the drawing surface info */
+    JAWT_DrawingSurfaceInfo* dsi = ds->GetDrawingSurfaceInfo(ds);
+    if (dsi == NULL) {
+        printf("Error getting surface info\n");
+        ds->Unlock(ds);
+        return;
+    }
+
+    /* Get the platform-specific drawing info */
+    JAWT_Win32DrawingSurfaceInfo* dsi_win =
+        (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo;
+
+    /* Now paint */
+    PAINTSTRUCT ps;
+    /* Do not use the HDC returned from BeginPaint()!! */
+    ::BeginPaint(dsi_win->hwnd, &ps);
+    HBRUSH hbrush = (HBRUSH)::GetStockObject(BLACK_BRUSH);
+    RECT rect;
+    rect.left = 5;
+    rect.top = 5;
+    rect.right = 95;
+    rect.bottom = 95;
+    ::FillRect(dsi_win->hdc, &rect, hbrush);
+    ::EndPaint(dsi_win->hwnd, &ps);
+
+    jobject ref = awt.GetComponent(env, (void*)(dsi_win->hwnd));
+    if (!env->IsSameObject(ref, canvas)) {
+        printf("Error! Different objects!\n");
+    }
+
+    /* Free the drawing surface info */
+    ds->FreeDrawingSurfaceInfo(dsi);
+
+    /* Unlock the drawing surface */
+    ds->Unlock(ds);
+
+    /* Free the drawing surface */
+    awt.FreeDrawingSurface(ds);
+}
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/event/KeyEvent/DeadKey/deadKeyMacOSX.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 7196547
+ * @summary Dead Key implementation for KeyEvent on Mac OS X
+ * @author alexandr.scherbatiy area=awt.event
+ * @run main deadKeyMacOSX
+ */
+
+import java.awt.*;
+import java.awt.event.*;
+import java.awt.event.KeyEvent;
+import sun.awt.OSInfo;
+import sun.awt.SunToolkit;
+
+public class deadKeyMacOSX {
+
+    private static SunToolkit toolkit;
+    private static volatile int state = 0;
+
+    public static void main(String[] args) throws Exception {
+
+        if (OSInfo.getOSType() != OSInfo.OSType.MACOSX) {
+            return;
+        }
+
+        toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
+        Robot robot = new Robot();
+        robot.setAutoDelay(50);
+
+        createAndShowGUI();
+
+        // Pressed keys: Alt + E + A
+        // Results:  ALT + VK_DEAD_ACUTE + a with accute accent
+        robot.keyPress(KeyEvent.VK_ALT);
+        robot.keyPress(KeyEvent.VK_E);
+        robot.keyRelease(KeyEvent.VK_E);
+        robot.keyRelease(KeyEvent.VK_ALT);
+
+        robot.keyPress(KeyEvent.VK_A);
+        robot.keyRelease(KeyEvent.VK_A);
+
+        if (state != 3) {
+            throw new RuntimeException("Wrong number of key events.");
+        }
+    }
+
+    static void createAndShowGUI() {
+        Frame frame = new Frame();
+        frame.setSize(300, 300);
+        Panel panel = new Panel();
+        panel.addKeyListener(new DeadKeyListener());
+        frame.add(panel);
+        frame.setVisible(true);
+        toolkit.realSync();
+
+        panel.requestFocusInWindow();
+        toolkit.realSync();
+    }
+
+    static class DeadKeyListener extends KeyAdapter {
+
+        @Override
+        public void keyPressed(KeyEvent e) {
+            int keyCode = e.getKeyCode();
+            char keyChar = e.getKeyChar();
+
+            switch (state) {
+                case 0:
+                    if (keyCode != KeyEvent.VK_ALT) {
+                        throw new RuntimeException("Alt is not pressed.");
+                    }
+                    state++;
+                    break;
+                case 1:
+                    if (keyCode != KeyEvent.VK_DEAD_ACUTE) {
+                        throw new RuntimeException("Dead ACUTE is not pressed.");
+                    }
+                    if (keyChar != 0xB4) {
+                        throw new RuntimeException("Pressed char is not dead acute.");
+                    }
+
+                    state++;
+                    break;
+                case 2:
+                    if (keyCode != KeyEvent.VK_A) {
+                        throw new RuntimeException("A is not pressed.");
+                    }
+                    if (keyChar != 0xE1) {
+                        throw new RuntimeException("A char does not have ACCUTE accent");
+                    }
+                    state++;
+                    break;
+                default:
+                    throw new RuntimeException("Excessive keyPressed event.");
+            }
+        }
+
+        @Override
+        public void keyTyped(KeyEvent e) {
+            int keyCode = e.getKeyCode();
+            char keyChar = e.getKeyChar();
+
+            if (state == 3) {
+                if (keyCode != 0) {
+                    throw new RuntimeException("Key code should be undefined.");
+                }
+                if (keyChar != 0xE1) {
+                    throw new RuntimeException("A char does not have ACCUTE accent");
+                }
+            } else {
+                throw new RuntimeException("Wron number of keyTyped events.");
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/beans/Introspector/Test7193977.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 7193977
+ * @summary Tests that generified property descriptors do not loose additional info
+ * @author Sergey Malenkov
+ */
+
+import java.awt.Image;
+import java.beans.BeanDescriptor;
+import java.beans.BeanInfo;
+import java.beans.EventSetDescriptor;
+import java.beans.IntrospectionException;
+import java.beans.Introspector;
+import java.beans.MethodDescriptor;
+import java.beans.PropertyDescriptor;
+import java.util.Arrays;
+import java.util.List;
+
+public class Test7193977 {
+
+    private static final List<String> names = Arrays.asList("listType", "list", "value");
+
+    public static void main(String args[]) {
+        for (String name : names) {
+            test(Abstract.class, name);
+            test(Concrete.class, name);
+        }
+    }
+
+    private static void test(Class<?> type, String name) {
+        if (!Boolean.TRUE.equals(BeanUtils.getPropertyDescriptor(type, name).getValue("transient"))) {
+            throw new Error("property '" + name + "' is not transient");
+        }
+    }
+
+    public static final class Concrete extends Abstract<String> {
+    }
+
+    public static abstract class Abstract<T> {
+        private List<T> list;
+
+        public List<T> getList() {
+            return this.list;
+        }
+
+        public void setList(List<T> list) {
+            this.list = list;
+        }
+
+        public T getValue(int index) {
+            return (0 <= index) && (this.list != null) && (index < this.list.size())
+                    ? this.list.get(index)
+                    : null;
+        }
+
+        public void setValue(int index, T value) {
+            if ((0 <= index) && (this.list != null)) {
+                if (index == this.list.size()) {
+                    this.list.add(value);
+                }
+                else if (index < this.list.size()) {
+                    this.list.set(index, value);
+                }
+            }
+        }
+
+        public String getListType() {
+            return (this.list != null)
+                    ? this.list.getClass().getName()
+                    : null;
+        }
+
+        public void setListType(String type) throws Exception {
+            this.list = (type != null)
+                    ? (List<T>) Class.forName(type).newInstance()
+                    : null;
+        }
+    }
+
+    public static final class ConcreteBeanInfo extends Wrapper {
+        public ConcreteBeanInfo() throws IntrospectionException {
+            super(Concrete.class);
+        }
+    }
+
+    public static final class AbstractBeanInfo extends Wrapper {
+        public AbstractBeanInfo() throws IntrospectionException {
+            super(Abstract.class);
+            for (PropertyDescriptor pd : getPropertyDescriptors()) {
+                if (names.contains(pd.getName())) {
+                    pd.setValue("transient", Boolean.TRUE);
+                }
+            }
+        }
+    }
+
+    private static class Wrapper implements BeanInfo {
+        private final BeanInfo info;
+
+        Wrapper(Class<?> type) throws IntrospectionException {
+            this.info = Introspector.getBeanInfo(type, Introspector.IGNORE_IMMEDIATE_BEANINFO);
+        }
+
+        public BeanDescriptor getBeanDescriptor() {
+            return this.info.getBeanDescriptor();
+        }
+
+        public EventSetDescriptor[] getEventSetDescriptors() {
+            return this.info.getEventSetDescriptors();
+        }
+
+        public int getDefaultEventIndex() {
+            return this.info.getDefaultEventIndex();
+        }
+
+        public PropertyDescriptor[] getPropertyDescriptors() {
+            return this.info.getPropertyDescriptors();
+        }
+
+        public int getDefaultPropertyIndex() {
+            return this.info.getDefaultPropertyIndex();
+        }
+
+        public MethodDescriptor[] getMethodDescriptors() {
+            return this.info.getMethodDescriptors();
+        }
+
+        public BeanInfo[] getAdditionalBeanInfo() {
+            return this.info.getAdditionalBeanInfo();
+        }
+
+        public Image getIcon(int kind) {
+            return this.info.getIcon(kind);
+        }
+    }
+}
--- a/test/java/lang/management/ManagementFactory/ThreadMXBeanProxy.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/lang/management/ManagementFactory/ThreadMXBeanProxy.java	Wed Sep 26 22:22:51 2012 -0700
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug     5086470 6358247
+ * @bug     5086470 6358247 7193302
  * @summary Test type conversion when invoking ThreadMXBean.dumpAllThreads
  *          through proxy.
  *
@@ -173,6 +173,10 @@
                 throw new RuntimeException("LockInfo: " + syncs[0] +
                     " IdentityHashCode not matched. Expected: " + hcode);
             }
+            LockInfo li = info.getLockInfo();
+            if (li == null) {
+                throw new RuntimeException("Expected non-null LockInfo");
+            }
         }
     }
     static class Mutex implements Lock, java.io.Serializable {
--- a/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java	Wed Sep 26 22:22:51 2012 -0700
@@ -48,7 +48,7 @@
     private static Map<String, PoolRecord> result = new HashMap<>();
     private static boolean trace = false;
     private static boolean testFailed = false;
-    private static final int EXPECTED_NUM_POOLS = 2;
+    private static int numMemoryPools = 1;
     private static final int NUM_GCS = 3;
     private static final int THRESHOLD = 10;
     private static Checker checker;
@@ -129,14 +129,19 @@
         for (MemoryPoolMXBean p : pools) {
             MemoryUsage u = p.getUsage();
             if (p.isUsageThresholdSupported() && p.isCollectionUsageThresholdSupported()) {
+                if (p.getName().toLowerCase().contains("perm")) {
+                    // if we have a "perm gen" pool increase the number of expected
+                    // memory pools by one.
+                    numMemoryPools++;
+                }
                 PoolRecord pr = new PoolRecord(p);
                 result.put(p.getName(), pr);
-                if (result.size() == EXPECTED_NUM_POOLS) {
+                if (result.size() == numMemoryPools) {
                     break;
                 }
             }
         }
-        if (result.size() != EXPECTED_NUM_POOLS) {
+        if (result.size() != numMemoryPools) {
             throw new RuntimeException("Unexpected number of selected pools");
         }
 
@@ -209,7 +214,7 @@
         public void run() {
             while (true) {
                 try {
-                    signals.acquire(EXPECTED_NUM_POOLS);
+                    signals.acquire(numMemoryPools);
                     checkResult();
                 } catch (InterruptedException e) {
                     throw new RuntimeException(e);
--- a/test/java/lang/management/MemoryMXBean/MemoryTest.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/lang/management/MemoryMXBean/MemoryTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -58,8 +58,11 @@
     // They are: Copy/Scavenger + MSC + CodeCache manager
     // (or equivalent for other collectors)
     // Number of GC memory managers = 2
-    private static int[] expectedMinNumPools = {3, 2};
-    private static int[] expectedMaxNumPools = {3, 4};
+
+    // Hotspot VM 1.8+ after perm gen removal is expected to have only
+    // one non-heap memory pool
+    private static int[] expectedMinNumPools = {3, 1};
+    private static int[] expectedMaxNumPools = {3, 1};
     private static int expectedNumGCMgrs = 2;
     private static int expectedNumMgrs = expectedNumGCMgrs + 1;
     private static String[] types = { "heap", "non-heap" };
@@ -80,6 +83,7 @@
 
     private static void checkMemoryPools() throws Exception {
         List pools = ManagementFactory.getMemoryPoolMXBeans();
+        boolean hasPerm = false;
 
         int[] numPools = new int[NUM_TYPES];
         for (ListIterator iter = pools.listIterator(); iter.hasNext();) {
@@ -90,6 +94,16 @@
             if (pool.getType() == MemoryType.NON_HEAP) {
                 numPools[NONHEAP]++;
             }
+            if (pool.getName().toLowerCase().contains("perm")) {
+                hasPerm = true;
+            }
+        }
+
+        if (hasPerm) {
+            // If the VM has perm gen there will be between 2 and 4 non heap
+            // pools (4 if class data sharing is used)
+            expectedMinNumPools[NONHEAP] = 2;
+            expectedMaxNumPools[NONHEAP] = 4;
         }
 
         // Check the number of Memory pools
--- a/test/java/net/Authenticator/B4678055.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/Authenticator/B4678055.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 4678055
  * @library ../../../sun/net/www/httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
+ * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main B4678055
  * @summary Basic Authentication fails with multiple realms
  */
@@ -119,13 +119,13 @@
         is.close();
     }
 
-    static HttpServer server;
+    static TestHttpServer server;
 
     public static void main (String[] args) throws Exception {
         MyAuthenticator auth = new MyAuthenticator ();
         Authenticator.setDefault (auth);
         try {
-            server = new HttpServer (new B4678055(), 1, 10, 0);
+            server = new TestHttpServer (new B4678055(), 1, 10, 0);
             System.out.println ("Server: listening on port: " + server.getLocalPort());
             client ("http://localhost:"+server.getLocalPort()+"/d1/foo.html");
             client ("http://localhost:"+server.getLocalPort()+"/d2/foo.html");
--- a/test/java/net/Authenticator/B4722333.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/Authenticator/B4722333.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 4722333
  * @library ../../../sun/net/www/httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
+ * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main B4722333
  * @summary JRE Proxy Authentication Not Working with ISA2000
  */
@@ -114,13 +114,13 @@
         is.close();
     }
 
-    static HttpServer server;
+    static TestHttpServer server;
 
     public static void main (String[] args) throws Exception {
         MyAuthenticator auth = new MyAuthenticator ();
         Authenticator.setDefault (auth);
         try {
-            server = new HttpServer (new B4722333(), 1, 10, 0);
+            server = new TestHttpServer (new B4722333(), 1, 10, 0);
             System.out.println ("Server started: listening on port: " + server.getLocalPort());
             client ("http://localhost:"+server.getLocalPort()+"/d1/d2/d3/foo.html");
             client ("http://localhost:"+server.getLocalPort()+"/ASD/d3/x.html");
--- a/test/java/net/Authenticator/B4759514.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/Authenticator/B4759514.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 4759514
  * @library ../../../sun/net/www/httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
+ * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main B4759514
  * @summary Digest Authentication is erroniously quoting the nc value, contrary to RFC 2617
  */
@@ -91,13 +91,13 @@
         is.close();
     }
 
-    static HttpServer server;
+    static TestHttpServer server;
 
     public static void main (String[] args) throws Exception {
         MyAuthenticator auth = new MyAuthenticator ();
         Authenticator.setDefault (auth);
         try {
-            server = new HttpServer (new B4759514(), 1, 10, 0);
+            server = new TestHttpServer (new B4759514(), 1, 10, 0);
             System.out.println ("Server: listening on port: " + server.getLocalPort());
             client ("http://localhost:"+server.getLocalPort()+"/d1/foo.html");
         } catch (Exception e) {
--- a/test/java/net/Authenticator/B4769350.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/Authenticator/B4769350.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 4769350
  * @library ../../../sun/net/www/httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction AbstractCallback
+ * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction AbstractCallback
  * @run main/othervm B4769350 server
  * @run main/othervm B4769350 proxy
  * @summary proxy authentication username and password caching only works in serial case
@@ -142,10 +142,10 @@
             switch (count) {
             case 0:
                 errorReply (req, "Basic realm=\"realm1\"");
-                HttpServer.rendezvous ("one", 2);
+                TestHttpServer.rendezvous ("one", 2);
                 break;
             case 1:
-                HttpServer.waitForCondition ("cond2");
+                TestHttpServer.waitForCondition ("cond2");
                 okReply (req);
                 break;
             default:
@@ -158,11 +158,11 @@
             switch (count) {
             case 0:
                 errorReply (req, "Basic realm=\"realm2\"");
-                HttpServer.rendezvous ("one", 2);
-                HttpServer.setCondition ("cond1");
+                TestHttpServer.rendezvous ("one", 2);
+                TestHttpServer.setCondition ("cond1");
                 break;
             case 1:
-                HttpServer.waitForCondition ("cond2");
+                TestHttpServer.waitForCondition ("cond2");
                 okReply (req);
                 break;
             default:
@@ -174,7 +174,7 @@
             switch (count) {
             case 0:
                 errorReply (req, "Basic realm=\"realm1\"");
-                HttpServer.rendezvous ("two", 2);
+                TestHttpServer.rendezvous ("two", 2);
                 break;
             case 1:
                 okReply (req);
@@ -188,8 +188,8 @@
             switch (count) {
             case 0:
                 errorReply (req, "Basic realm=\"realm2\"");
-                HttpServer.rendezvous ("two", 2);
-                HttpServer.setCondition ("cond2");
+                TestHttpServer.rendezvous ("two", 2);
+                TestHttpServer.setCondition ("cond2");
                 break;
             case 1:
                 okReply (req);
@@ -207,7 +207,7 @@
         void doT2a (HttpTransaction req, int count) throws IOException {
             /* This will be called several times */
             if (count == 1) {
-                HttpServer.setCondition ("T2cond1");
+                TestHttpServer.setCondition ("T2cond1");
             }
             errorReply (req, "Basic realm=\"realm3\"");
         }
@@ -233,7 +233,7 @@
             switch (count) {
             case 0:
                 proxyReply (req, "Basic realm=\"proxy\"");
-                HttpServer.setCondition ("T3cond1");
+                TestHttpServer.setCondition ("T3cond1");
                 break;
             case 1:
                 errorReply (req, "Basic realm=\"realm4\"");
@@ -260,7 +260,7 @@
         }
     };
 
-    static HttpServer server;
+    static TestHttpServer server;
     static MyAuthenticator auth = new MyAuthenticator ();
 
     static int redirects = 4;
@@ -276,7 +276,7 @@
         c4 = new Client (authority, "/test/realm2/t1d", false);
 
         c1.start(); c2.start();
-        HttpServer.waitForCondition ("cond1");
+        TestHttpServer.waitForCondition ("cond1");
         c3.start(); c4.start();
         c1.join(); c2.join(); c3.join(); c4.join();
 
@@ -294,7 +294,7 @@
         c5 = new Client (authority, "/test/realm3/t2a", true);
         c6 = new Client (authority, "/test/realm3/t2b", false);
         c5.start ();
-        HttpServer.waitForCondition ("T2cond1");
+        TestHttpServer.waitForCondition ("T2cond1");
         c6.start ();
         c5.join(); c6.join();
 
@@ -313,7 +313,7 @@
         c8 = new Client (authority, "/test/realm4/t3b", false);
         c9 = new Client (authority, "/test/realm4/t3c", false);
         c7.start ();
-        HttpServer.waitForCondition ("T3cond1");
+        TestHttpServer.waitForCondition ("T3cond1");
         c8.start ();
         c9.start ();
         c7.join(); c8.join(); c9.join();
@@ -333,7 +333,7 @@
         Authenticator.setDefault (auth);
         boolean proxy = args[0].equals ("proxy");
         try {
-            server = new HttpServer (new CallBack(), 10, 1, 0);
+            server = new TestHttpServer (new CallBack(), 10, 1, 0);
             System.out.println ("Server: listening on port: " + server.getLocalPort());
             if (proxy) {
                 System.setProperty ("http.proxyHost", "localhost");
--- a/test/java/net/Authenticator/B4921848.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/Authenticator/B4921848.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 4921848
  * @library ../../../sun/net/www/httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
+ * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main/othervm -Dhttp.auth.preference=basic B4921848
  * @summary Allow user control over authentication schemes
  */
@@ -82,13 +82,13 @@
         is.close();
     }
 
-    static HttpServer server;
+    static TestHttpServer server;
 
     public static void main (String[] args) throws Exception {
         MyAuthenticator auth = new MyAuthenticator ();
         Authenticator.setDefault (auth);
         try {
-            server = new HttpServer (new B4921848(), 1, 10, 0);
+            server = new TestHttpServer (new B4921848(), 1, 10, 0);
             System.out.println ("Server started: listening on port: " + server.getLocalPort());
             client ("http://localhost:"+server.getLocalPort()+"/d1/d2/d3/foo.html");
         } catch (Exception e) {
--- a/test/java/net/Authenticator/B4933582.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/Authenticator/B4933582.java	Wed Sep 26 22:22:51 2012 -0700
@@ -119,7 +119,7 @@
         is.close();
     }
 
-    static HttpServer server;
+    static TestHttpServer server;
 
     public static void main (String[] args) throws Exception {
         firstTime = args[0].equals ("first");
@@ -128,11 +128,11 @@
         CacheImpl cache;
         try {
             if (firstTime) {
-                server = new HttpServer (new B4933582(), 1, 10, 0);
+                server = new TestHttpServer (new B4933582(), 1, 10, 0);
                 cache = new CacheImpl (server.getLocalPort());
             } else {
                 cache = new CacheImpl ();
-                server = new HttpServer(new B4933582(), 1, 10, cache.getPort());
+                server = new TestHttpServer(new B4933582(), 1, 10, cache.getPort());
             }
             AuthCacheValue.setAuthCache (cache);
             System.out.println ("Server: listening on port: " + server.getLocalPort());
--- a/test/java/net/Authenticator/B4962064.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/Authenticator/B4962064.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 4962064
  * @library ../../../sun/net/www/httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
+ * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main/othervm B4962064
  * @summary Extend Authenticator to provide access to request URI and server/proxy
  */
@@ -85,12 +85,12 @@
         is.close();
     }
 
-    static HttpServer server;
+    static TestHttpServer server;
     static URL urlsave;
 
     public static void main (String[] args) throws Exception {
         try {
-            server = new HttpServer (new B4962064(), 1, 10, 0);
+            server = new TestHttpServer (new B4962064(), 1, 10, 0);
             int port = server.getLocalPort();
             System.setProperty ("http.proxyHost", "localhost");
             System.setProperty ("http.proxyPort", Integer.toString (port));
--- a/test/java/net/CookieHandler/CookieManagerTest.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/CookieHandler/CookieManagerTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -26,7 +26,7 @@
  * @summary Unit test for java.net.CookieManager
  * @bug 6244040
  * @library ../../../sun/net/www/httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
+ * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main/othervm -ea CookieManagerTest
  * @author Edward Wang
  */
@@ -38,7 +38,7 @@
 
 public class CookieManagerTest {
     static CookieHttpTransaction httpTrans;
-    static HttpServer server;
+    static TestHttpServer server;
 
     public static void main(String[] args) throws Exception {
         startHttpServer();
@@ -52,7 +52,7 @@
     public static void startHttpServer() {
         try {
             httpTrans = new CookieHttpTransaction();
-            server = new HttpServer(httpTrans, 1, 1, 0);
+            server = new TestHttpServer(httpTrans, 1, 1, 0);
         } catch (IOException e) {
             e.printStackTrace();
         }
--- a/test/java/net/InetAddress/GetLocalHostWithSM.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/InetAddress/GetLocalHostWithSM.java	Wed Sep 26 22:22:51 2012 -0700
@@ -41,14 +41,13 @@
         public static void main(String[] args) throws Exception {
 
             // try setting the local hostname
-            try {
-                System.setProperty("host.name", InetAddress.
-                                                getLocalHost().
-                                                getHostName());
-            } catch (UnknownHostException e) {
-                System.out.println("Cannot find the local hostname, " +
-                        "no nameserver entry found");
+            InetAddress localHost = InetAddress.getLocalHost();
+            if (localHost.isLoopbackAddress()) {
+                System.err.println("Local host name is resolved into a loopback address. Quit now!");
+                return;
             }
+            System.setProperty("host.name", localHost.
+                                            getHostName());
             String policyFileName = System.getProperty("test.src", ".") +
                           "/" + "policy.file";
             System.setProperty("java.security.policy", policyFileName);
@@ -66,6 +65,7 @@
                                 new MyAction(), null);
 
             if (localHost1.equals(localHost2)) {
+                System.out.println("localHost1 = " + localHost1);
                 throw new RuntimeException("InetAddress.getLocalHost() test " +
                                            " fails. localHost2 should be " +
                                            " the real address instead of " +
--- a/test/java/net/ProxySelector/LoopbackAddresses.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/ProxySelector/LoopbackAddresses.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @bug 4924226
  * @summary PIT: Can no launch jnlp application via 127.0.0.1 address on the web server
  * @library ../../../sun/net/www/httptest/
- * @build ClosedChannelList HttpServer HttpTransaction HttpCallback
+ * @build ClosedChannelList TestHttpServer HttpTransaction HttpCallback
  * @compile LoopbackAddresses.java
  * @run main/othervm LoopbackAddresses
  */
@@ -39,7 +39,7 @@
  */
 
 public class LoopbackAddresses implements HttpCallback {
-    static HttpServer server;
+    static TestHttpServer server;
 
     public void request (HttpTransaction req) {
         req.setResponseEntityBody ("Hello .");
@@ -52,7 +52,7 @@
 
     public static void main(String[] args) {
         try {
-            server = new HttpServer (new LoopbackAddresses(), 1, 10, 0);
+            server = new TestHttpServer (new LoopbackAddresses(), 1, 10, 0);
             ProxyServer pserver = new ProxyServer(InetAddress.getByName("localhost"), server.getLocalPort());
             // start proxy server
             new Thread(pserver).start();
--- a/test/java/net/ProxySelector/ProxyTest.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/ProxySelector/ProxyTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -26,7 +26,7 @@
  * @bug 4696512
  * @summary HTTP client: Improve proxy server configuration and selection
  * @library ../../../sun/net/www/httptest/
- * @build ClosedChannelList HttpServer HttpTransaction HttpCallback
+ * @build ClosedChannelList TestHttpServer HttpTransaction HttpCallback
  * @compile ProxyTest.java
  * @run main/othervm -Dhttp.proxyHost=inexistant -Dhttp.proxyPort=8080 ProxyTest
  */
@@ -36,7 +36,7 @@
 import java.util.ArrayList;
 
 public class ProxyTest implements HttpCallback {
-    static HttpServer server;
+    static TestHttpServer server;
 
     public ProxyTest() {
     }
@@ -74,7 +74,7 @@
             throw new RuntimeException("Default ProxySelector is null");
         ProxySelector.setDefault(new MyProxySelector());
         try {
-            server = new HttpServer (new ProxyTest(), 1, 10, 0);
+            server = new TestHttpServer (new ProxyTest(), 1, 10, 0);
             URL url = new URL("http://localhost:"+server.getLocalPort());
             System.out.println ("client opening connection to: " + url);
             HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
--- a/test/java/net/URL/PerConnectionProxy.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/URL/PerConnectionProxy.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @bug 4920526
  * @summary Needs per connection proxy support for URLs
  * @library ../../../sun/net/www/httptest/
- * @build ClosedChannelList HttpServer HttpTransaction HttpCallback
+ * @build ClosedChannelList TestHttpServer HttpTransaction HttpCallback
  * @compile PerConnectionProxy.java
  * @run main/othervm -Dhttp.proxyHost=inexistant -Dhttp.proxyPort=8080 PerConnectionProxy
  */
@@ -35,7 +35,7 @@
 import sun.net.www.*;
 
 public class PerConnectionProxy implements HttpCallback {
-    static HttpServer server;
+    static TestHttpServer server;
 
     public void request (HttpTransaction req) {
         req.setResponseEntityBody ("Hello .");
@@ -48,7 +48,7 @@
 
     public static void main(String[] args) {
         try {
-            server = new HttpServer (new PerConnectionProxy(), 1, 10, 0);
+            server = new TestHttpServer (new PerConnectionProxy(), 1, 10, 0);
             ProxyServer pserver = new ProxyServer(InetAddress.getByName("localhost"), server.getLocalPort());
             // start proxy server
             new Thread(pserver).start();
--- a/test/java/net/URLClassLoader/closetest/CloseTest.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/URLClassLoader/closetest/CloseTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -128,7 +128,7 @@
         // load tests
         loadClass ("com.foo.TestClass1", loader, false);
         loadClass ("com.foo.TestClass", loader, true);
-        loadClass ("java.awt.Button", loader, true);
+        loadClass ("java.sql.Array", loader, true);
 
         // now check we can delete the path
         rm_minus_rf (new File(name));
--- a/test/java/net/URLConnection/B5052093.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/net/URLConnection/B5052093.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 5052093
  * @library ../../../sun/net/www/httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
+ * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main B5052093
  * @summary URLConnection doesn't support large files
  */
@@ -34,7 +34,7 @@
 import sun.net.www.protocol.file.FileURLConnection;
 
 public class B5052093 implements HttpCallback {
-    private static HttpServer server;
+    private static TestHttpServer server;
     private static long testSize = ((long) (Integer.MAX_VALUE)) + 2;
 
     public static class LargeFile extends File {
@@ -63,7 +63,7 @@
     }
 
     public static void main(String[] args) throws Exception {
-        server = new HttpServer(new B5052093(), 1, 10, 0);
+        server = new TestHttpServer(new B5052093(), 1, 10, 0);
         try {
             URL url = new URL("http://localhost:"+server.getLocalPort()+"/foo");
             URLConnection conn = url.openConnection();
--- a/test/java/nio/channels/AsyncCloseAndInterrupt.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/nio/channels/AsyncCloseAndInterrupt.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,17 +22,24 @@
  */
 
 /* @test
- * @bug 4460583 4470470 4840199 6419424 6710579 6596323 6824135 6395224
+ * @bug 4460583 4470470 4840199 6419424 6710579 6596323 6824135 6395224 7142919
+ * @run main/othervm AsyncCloseAndInterrupt
  * @summary Comprehensive test of asynchronous closing and interruption
  * @author Mark Reinhold
  */
 
 import java.io.*;
 import java.net.*;
-import java.nio.*;
 import java.nio.channels.*;
-import java.util.*;
-
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
 
 public class AsyncCloseAndInterrupt {
 
@@ -79,45 +86,12 @@
     // Server socket that refuses all connections
 
     static ServerSocketChannel refuser;
-    static List refuserClients = new ArrayList();
 
     private static void initRefuser() throws IOException {
         refuser = ServerSocketChannel.open();
         refuser.socket().bind(wildcardAddress);
-        pumpRefuser("Initializing refuser...");
     }
 
-    private static void pumpRefuser(String msg) throws IOException {
-        // Can't reliably saturate connection backlog on Windows Server editions
-        assert !TestUtil.onWindows();
-
-        log.print(msg);
-        int n = refuserClients.size();
-
-        // Saturate the refuser's connection backlog so that further connection
-        // attempts will block
-        //
-        outer:
-        for (;;) {
-            SocketChannel sc = SocketChannel.open();
-            sc.configureBlocking(false);
-            if (!sc.connect(refuser.socket().getLocalSocketAddress())) {
-                for (int i = 0; i < 20; i++) {
-                    Thread.yield();
-                    if (sc.finishConnect())
-                        break;
-                    if (i >= 19)
-                        break outer;
-                }
-            }
-            // Retain so that finalizer doesn't close
-            refuserClients.add(sc);
-        }
-
-        log.println("  " + (refuserClients.size() - n) + " connections");
-    }
-
-
     // Dead pipe source and sink
 
     static Pipe.SourceChannel deadSource;
@@ -374,8 +348,8 @@
         };
 
     static final Op CONNECT = new Op("connect") {
-            void setup() throws IOException {
-                pumpRefuser("Pumping refuser ...");
+            void setup() {
+                waitPump("connect wait for pumping refuser ...");
             }
             void doIO(InterruptibleChannel ich) throws IOException {
                 SocketChannel sc = (SocketChannel)ich;
@@ -386,8 +360,8 @@
         };
 
     static final Op FINISH_CONNECT = new Op("finishConnect") {
-            void setup() throws IOException {
-                pumpRefuser("Pumping refuser ...");
+            void setup() {
+                waitPump("finishConnect wait for pumping refuser ...");
             }
             void doIO(InterruptibleChannel ich) throws IOException {
                 SocketChannel sc = (SocketChannel)ich;
@@ -462,6 +436,7 @@
             this.test = test;
         }
 
+        @SuppressWarnings("fallthrough")
         private void caught(Channel ch, IOException x) {
             String xn = x.getClass().getName();
             switch (test) {
@@ -519,9 +494,63 @@
 
     }
 
+    private static volatile boolean pumpDone = false;
+    private static volatile boolean pumpReady = false;
 
-    // Tests
+    private static void waitPump(String msg){
+        pumpReady = false;
+        log.println(msg);
+
+        while (!pumpReady){
+            sleep(200);
+        }
+    }
+
+    // Create a pump thread dedicated to saturate refuser's connection backlog
+    private static Future<Integer> pumpRefuser(ExecutorService pumperExecutor) {
+
+        Callable<Integer> pumpTask = new Callable<Integer>() {
+
+            @Override
+            public Integer call() throws IOException {
+                // Can't reliably saturate connection backlog on Windows Server editions
+                assert !TestUtil.onWindows();
+                log.println("Start pumping refuser ...");
+                List<SocketChannel> refuserClients = new ArrayList<>();
 
+                // Saturate the refuser's connection backlog so that further connection
+                // attempts will be blocked
+                while (!pumpDone) {
+                    SocketChannel sc = SocketChannel.open();
+                    sc.configureBlocking(false);
+                    boolean connected = sc.connect(refuser.socket().getLocalSocketAddress());
+
+                    // Assume that the connection backlog is saturated if a
+                    // client cannot connect to the refuser within 50 miliseconds
+                    long start = System.currentTimeMillis();
+                    while (!connected && (System.currentTimeMillis() - start < 50)) {
+                        connected = sc.finishConnect();
+                    }
+
+                    if (connected) {
+                        // Retain so that finalizer doesn't close
+                        refuserClients.add(sc);
+                        pumpReady = false;
+                    } else {
+                        sc.close();
+                        pumpReady = true;
+                    }
+                }
+
+                log.println("Stop pumping refuser ...");
+                return refuserClients.size();
+            }
+        };
+
+        return pumperExecutor.submit(pumpTask);
+    }
+
+    // Test
     static void test(ChannelFactory cf, Op op, int test)
         throws Exception
     {
@@ -667,15 +696,40 @@
             log.println("WARNING Cannot reliably test connect/finishConnect"
                 + " operations on Windows");
         } else {
-            test(socketChannelFactory, CONNECT);
-            test(socketChannelFactory, FINISH_CONNECT);
+            // Only the following tests need refuser's connection backlog
+            // to be saturated
+            ExecutorService pumperExecutor =
+                    Executors.newSingleThreadExecutor(
+                    new ThreadFactory() {
+
+                        @Override
+                        public Thread newThread(Runnable r) {
+                            Thread t = new Thread(r);
+                            t.setDaemon(true);
+                            t.setName("Pumper");
+                            return t;
+                        }
+                    });
+
+            pumpDone = false;
+            try {
+                Future<Integer> pumpFuture = pumpRefuser(pumperExecutor);
+                waitPump("\nWait for initial Pump");
+
+                test(socketChannelFactory, CONNECT);
+                test(socketChannelFactory, FINISH_CONNECT);
+
+                pumpDone = true;
+                Integer newConn = pumpFuture.get(30, TimeUnit.SECONDS);
+                log.println("Pump " + newConn + " connections.");
+            } finally {
+                pumperExecutor.shutdown();
+            }
         }
 
         test(serverSocketChannelFactory, ACCEPT);
         test(datagramChannelFactory);
         test(pipeSourceChannelFactory);
         test(pipeSinkChannelFactory);
-
     }
-
 }
--- a/test/java/util/Currency/PropertiesTest.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/util/Currency/PropertiesTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,11 +22,12 @@
  */
 
 import java.io.*;
+import java.text.*;
 import java.util.*;
 import java.util.regex.*;
 
 public class PropertiesTest {
-    public static void main(String[] s) {
+    public static void main(String[] s) throws Exception {
         for (int i = 0; i < s.length; i ++) {
             if ("-d".equals(s[i])) {
                 i++;
@@ -76,7 +77,7 @@
         pw.close();
     }
 
-    private static void compare(String beforeFile, String afterFile) {
+    private static void compare(String beforeFile, String afterFile) throws Exception {
         // load file contents
         Properties before = new Properties();
         Properties after = new Properties();
@@ -114,11 +115,23 @@
         // test each replacements
         keys = p.stringPropertyNames();
         Pattern propertiesPattern =
-            Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*([0-3])");
+            Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*" +
+                "([0-3])\\s*,?\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:" +
+                "\\d{2}:\\d{2})?");
         for (String key: keys) {
             String val = p.getProperty(key);
+            try {
+                if (countOccurrences(val, ',') == 3 && !isPastCutoverDate(val)) {
+                    System.out.println("Skipping since date is in future");
+                    continue; // skip since date in future (no effect)
+                }
+            } catch (ParseException pe) {
+                // swallow - currency class should not honour this value
+                continue;
+            }
             String afterVal = after.getProperty(key);
             System.out.printf("Testing key: %s, val: %s... ", key, val);
+            System.out.println("AfterVal is : " + afterVal);
 
             Matcher m = propertiesPattern.matcher(val.toUpperCase(Locale.ROOT));
             if (!m.find()) {
@@ -131,7 +144,6 @@
                 // ignore this
                 continue;
             }
-
             Matcher mAfter = propertiesPattern.matcher(afterVal);
             mAfter.find();
 
@@ -164,4 +176,29 @@
             throw new RuntimeException(sb.toString());
         }
     }
+
+    private static boolean isPastCutoverDate(String s)
+            throws IndexOutOfBoundsException, NullPointerException, ParseException {
+        String dateString = s.substring(s.lastIndexOf(',')+1, s.length()).trim();
+        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT);
+        format.setTimeZone(TimeZone.getTimeZone("GMT"));
+        format.setLenient(false);
+
+        long time = format.parse(dateString).getTime();
+        if (System.currentTimeMillis() - time >= 0L) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    private static int countOccurrences(String value, char match) {
+        int count = 0;
+        for (char c : value.toCharArray()) {
+            if (c == match) {
+               ++count;
+            }
+        }
+        return count;
+    }
 }
--- a/test/java/util/Currency/PropertiesTest.sh	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/util/Currency/PropertiesTest.sh	Wed Sep 26 22:22:51 2012 -0700
@@ -1,7 +1,7 @@
 #!/bin/sh
 #
 # @test
-# @bug 6332666
+# @bug 6332666 7180362
 # @summary tests the capability of replacing the currency data with user
 #     specified currency properties file
 # @build PropertiesTest
--- a/test/java/util/Currency/currency.properties	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/util/Currency/currency.properties	Wed Sep 26 22:22:51 2012 -0700
@@ -2,9 +2,19 @@
 # Test data for replacing the currency data
 #
 JP=JPZ,123,2
-US=euR,978,2
+ES=ESD,877,2
+US=euR,978,2,2001-01-01T00:00:00
+CM=IED,111,2, 2004-01-01T00:70:00
+SB=EUR,111,2, 2099-01-01T00:00:00
 ZZ	=	ZZZ	,	999	,	3
+NO=EUR   ,978  ,2,  2099-01-01T00:00:00
 
 # invalid entries
 GB=123
 FR=zzzzz.123
+DE=2009-01-01T00:00:00,EUR,111,2
+IE=euR,111,2,#testcomment
+=euR,111,2, 2099-01-01-00-00-00
+FM=DED,194,2,eeee-01-01T00:00:00
+PE=EUR   ,978  ,2,  20399-01-01T00:00:00
+MX=SSS,493,2,2001-01-01-00-00-00
--- a/test/java/util/Map/Collisions.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/java/util/Map/Collisions.java	Wed Sep 26 22:22:51 2012 -0700
@@ -24,6 +24,8 @@
 /*
  * @test
  * @bug 7126277
+ * @run main Collisions -shortrun
+ * @run main/othervm -Djdk.map.althashing.threshold=0 Collisions -shortrun
  * @summary Ensure Maps behave well with lots of hashCode() collisions.
  * @author Mike Duigou
  */
@@ -33,6 +35,11 @@
 
 public class Collisions {
 
+    /**
+     * Number of elements per map.
+     */
+    private static final int TEST_SIZE = 5000;
+
     final static class HashableInteger implements Comparable<HashableInteger> {
 
         final int value;
@@ -64,20 +71,19 @@
             return value - o.value;
         }
 
+        @Override
         public String toString() {
             return Integer.toString(value);
         }
     }
-    private static final int ITEMS = 5000;
-    private static final Object KEYS[][];
 
-    static {
-        HashableInteger UNIQUE_OBJECTS[] = new HashableInteger[ITEMS];
-        HashableInteger COLLIDING_OBJECTS[] = new HashableInteger[ITEMS];
-        String UNIQUE_STRINGS[] = new String[ITEMS];
-        String COLLIDING_STRINGS[] = new String[ITEMS];
+    private static Object[][] makeTestData(int size) {
+        HashableInteger UNIQUE_OBJECTS[] = new HashableInteger[size];
+        HashableInteger COLLIDING_OBJECTS[] = new HashableInteger[size];
+        String UNIQUE_STRINGS[] = new String[size];
+        String COLLIDING_STRINGS[] = new String[size];
 
-        for (int i = 0; i < ITEMS; i++) {
+        for (int i = 0; i < size; i++) {
             UNIQUE_OBJECTS[i] = new HashableInteger(i, Integer.MAX_VALUE);
             COLLIDING_OBJECTS[i] = new HashableInteger(i, 10);
             UNIQUE_STRINGS[i] = unhash(i);
@@ -86,7 +92,7 @@
                     : "\u0000\u0000\u0000\u0000\u0000" + COLLIDING_STRINGS[i - 1];
         }
 
-     KEYS = new Object[][] {
+     return new Object[][] {
             new Object[]{"Unique Objects", UNIQUE_OBJECTS},
             new Object[]{"Colliding Objects", COLLIDING_OBJECTS},
             new Object[]{"Unique Strings", UNIQUE_STRINGS},
@@ -132,23 +138,29 @@
     }
 
     private static void realMain(String[] args) throws Throwable {
-        for (Object[] keys_desc : KEYS) {
-            Map<Object, Object>[] MAPS = (Map<Object, Object>[]) new Map[]{
+        boolean shortRun = args.length > 0 && args[0].equals("-shortrun");
+
+        Object[][] mapKeys = makeTestData(shortRun ? (TEST_SIZE / 2) : TEST_SIZE);
+
+        // loop through data sets
+        for (Object[] keys_desc : mapKeys) {
+            Map<Object, Object>[] maps = (Map<Object, Object>[]) new Map[]{
+                        new HashMap<>(),
                         new Hashtable<>(),
-                        new HashMap<>(),
                         new IdentityHashMap<>(),
                         new LinkedHashMap<>(),
-                        new ConcurrentHashMap<>(),
+                        new TreeMap<>(),
                         new WeakHashMap<>(),
-                        new TreeMap<>(),
+                        new ConcurrentHashMap<>(),
                         new ConcurrentSkipListMap<>()
                     };
 
-            for (Map<Object, Object> map : MAPS) {
+            // for each map type.
+            for (Map<Object, Object> map : maps) {
                 String desc = (String) keys_desc[0];
                 Object[] keys = (Object[]) keys_desc[1];
                 try {
-                testMap(map, desc, keys);
+                    testMap(map, desc, keys);
                 } catch(Exception all) {
                     unexpected("Failed for " + map.getClass().getName() + " with " + desc, all);
                 }
@@ -397,7 +409,7 @@
     }
 
     public static void main(String[] args) throws Throwable {
-        Thread.currentThread().setName("Collisions");
+        Thread.currentThread().setName(Collisions.class.getName());
 //        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
         try {
             realMain(args);
--- a/test/javax/imageio/metadata/BooleanAttributes.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/javax/imageio/metadata/BooleanAttributes.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,12 +1,10 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
+ * 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
--- a/test/javax/imageio/metadata/DOML3Node.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/javax/imageio/metadata/DOML3Node.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,12 +1,10 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
+ * 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
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/GetChildNames.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 4429876
+ * @run main GetChildNames
+ * @summary Tests that the getChildNames method of
+ * IIOMetadataFormatImpl returns null for a CHILD_POLICY_EMPTY node.
+ */
+
+import javax.imageio.metadata.IIOMetadataFormatImpl;
+import javax.imageio.ImageTypeSpecifier;
+
+public class GetChildNames {
+
+    public static void main(String argv[]) {
+        GCNFormatImpl fmt = new GCNFormatImpl("root", 1, 10);
+        fmt.addElement("cc", "root", fmt.CHILD_POLICY_EMPTY);
+
+        String[] result = fmt.getChildNames("cc");
+        if (result != null) {
+            throw new RuntimeException
+                ("Failed, result is not null: " + result);
+        }
+    }
+}
+
+class GCNFormatImpl extends IIOMetadataFormatImpl {
+
+    GCNFormatImpl(String root, int minChildren, int maxChildren) {
+        super(root, minChildren, maxChildren);
+    }
+
+    public void addElement(String elementName,
+                           String parentName, int childPolicy) {
+        super.addElement(elementName, parentName, childPolicy);
+    }
+
+    public boolean canNodeAppear(String elementName,
+                                 ImageTypeSpecifier imageType) {
+        return true;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/GetObjectMinValue.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 4429875 7186799
+ * @compile -source 1.4 GetObjectMinValue.java
+ * @run main GetObjectMinValue
+ * @summary Tests the getObject{Min,Max}Value method of
+ * IIOMetadataFormatImpl for an inclusive range
+ */
+
+// Compiled with -source 1.4 to work around javac bug 5041233
+
+import javax.imageio.metadata.IIOMetadataFormatImpl;
+import javax.imageio.ImageTypeSpecifier;
+
+public class GetObjectMinValue {
+
+    public static void main(String argv[]) {
+        test(true, true);
+        test(true, false);
+        test(false, true);
+        test(false, false);
+    }
+
+    private static void test(boolean minInclusive, boolean maxInclusive) {
+        Integer defValue = new Integer(1);
+        Integer minValue = new Integer(0);
+        Integer maxValue = new Integer(10);
+
+        MyFormatImpl fmt = new MyFormatImpl("root", 1, 10);
+
+        fmt.addObjectValue("root", defValue.getClass(), defValue,
+                           minValue, maxValue, minInclusive, maxInclusive);
+
+        try {
+            Integer act_min = (Integer)fmt.getObjectMinValue("root");
+            if (! act_min.equals(minValue))
+                throw new RuntimeException("invalid min value: " + act_min);
+        } catch (Throwable e) {
+            throw new RuntimeException
+                ("getObjectMinValue: unexpected exception: " + e);
+        }
+        try {
+            Integer act_max = (Integer)fmt.getObjectMaxValue("root");
+            if (! act_max.equals(maxValue))
+                throw new RuntimeException("invalid max value: " + act_max);
+        } catch (Throwable e) {
+            throw new RuntimeException
+                ("getObjectMaxValue: unexpected exception: " + e);
+        }
+    }
+
+    static class MyFormatImpl extends IIOMetadataFormatImpl {
+
+        MyFormatImpl(String root, int minChildren, int maxChildren) {
+            super(root, minChildren, maxChildren);
+        }
+
+        public void addObjectValue(String elementName,
+                                   Class classType, Object defaultValue,
+                                   Comparable minValue, Comparable maxValue,
+                                   boolean minInclusive, boolean maxInclusive) {
+            super.addObjectValue(elementName,
+                                 classType, defaultValue,
+                                 minValue, maxValue,
+                                 minInclusive, maxInclusive);
+        }
+
+        public boolean canNodeAppear(String elementName,
+                                     ImageTypeSpecifier imageType) {
+            return true;
+        }
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/IIOMetadataFormat/MetadataFormatTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @bug 4929170
+ * @summary  Tests that user-supplied IIOMetadata implementations
+ *           is able to load correspnding IIOMetadataFormat implementations.
+ */
+
+import java.io.File;
+import java.net.URL;
+import java.net.URLClassLoader;
+
+
+public class MetadataFormatTest {
+    public static void main(String[] args) throws Exception {
+        String codebase = args[0];
+        String code = args[1];
+
+        MetadataTest t = createTest(codebase, code);
+        try {
+            t.doTest();
+        } catch (IllegalStateException e) {
+            System.out.println("Test failed.");
+            e.printStackTrace();
+
+            System.exit(1);
+        }
+    }
+
+    protected static MetadataTest createTest(String codebase,
+                                             String code) throws Exception {
+        URL[] urls = { new File(codebase).toURL()};
+        ClassLoader loader = new URLClassLoader(urls);
+
+        Class ct = loader.loadClass(code);
+
+        return (MetadataTest)ct.newInstance();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/IIOMetadataFormat/MetadataFormatThreadTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @bug 4929170
+ * @summary Tests that user-supplied IIOMetadata implementations
+ *           is able to load correspnding IIOMetadataFormat implementations.
+ */
+
+import java.io.File;
+import java.net.URL;
+import java.net.URLClassLoader;
+
+
+public class MetadataFormatThreadTest implements Runnable {
+
+    String test_class;
+
+    public static void main(String[] args) throws Exception {
+        String codebase = args[0];
+        String code = args[1];
+
+        Thread t = createTest(codebase, code);
+        try {
+            t.start();
+        } catch (IllegalStateException e) {
+            System.out.println("Test failed.");
+            e.printStackTrace();
+
+            System.exit(1);
+        }
+    }
+
+    public MetadataFormatThreadTest(String c) {
+        test_class = c;
+    }
+
+    public void run() {
+        try {
+            ClassLoader loader = (ClassLoader)
+                java.security.AccessController.doPrivileged(
+                    new java.security.PrivilegedAction() {
+                            public Object run() {
+                                return Thread.currentThread().getContextClassLoader();
+                            }
+                        });
+
+            Class ct = loader.loadClass(test_class);
+
+            MetadataTest t = (MetadataTest)ct.newInstance();
+
+            t.doTest();
+        } catch (Exception e) {
+            System.out.println("Test failed.");
+            e.printStackTrace();
+            System.exit(1);
+        }
+    }
+
+    protected static Thread createTest(String codebase,
+                                             String code) throws Exception {
+
+        URL[] urls = { new File(codebase).toURL()};
+        final ClassLoader loader = new URLClassLoader(urls);
+
+        final Thread t = new Thread(new MetadataFormatThreadTest(code));
+        java.security.AccessController.doPrivileged(
+            new java.security.PrivilegedAction() {
+                    public Object run() {
+                        t.setContextClassLoader(loader);
+                        return null;
+                    }
+                });
+
+        return t;
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/IIOMetadataFormat/MetadataTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @bug       4929170
+ * @summary   Interface for user-supplied IIOMetadata
+ *            implementation tests.
+ */
+
+import java.io.IOException;
+
+public interface MetadataTest {
+    public void doTest() throws IOException;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/IIOMetadataFormat/UserPluginMetadataFormatTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,467 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug     4929170
+ * @summary Tests that user-supplied IIOMetadata implementations loaded by
+ *           system class loader (i.e. corresponding classes are available via
+ *           classpath) is able to load correspnding IIOMetadataFormat
+ *           implementations.
+ * @run     main UserPluginMetadataFormatTest
+ */
+
+import java.awt.Rectangle;
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+import java.io.ByteArrayInputStream;
+import java.util.Iterator;
+import java.util.ListResourceBundle;
+import java.util.Locale;
+import java.util.MissingResourceException;
+import java.util.Vector;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
+import javax.imageio.ImageReadParam;
+import javax.imageio.IIOException;
+import javax.imageio.ImageTypeSpecifier;
+import javax.imageio.event.IIOReadWarningListener;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.metadata.IIOMetadataFormat;
+import javax.imageio.metadata.IIOMetadataFormatImpl;
+import javax.imageio.metadata.IIOInvalidTreeException;
+import javax.imageio.spi.ImageReaderSpi;
+import org.w3c.dom.Node;
+
+public class UserPluginMetadataFormatTest implements MetadataTest {
+
+    public static void main(String[] argv) throws IOException {
+        new UserPluginMetadataFormatTest().doTest();
+    }
+
+    public void doTest() throws IOException {
+
+        DummyImageReaderImpl reader;
+
+        reader = new DummyImageReaderImpl(new DummyImageReaderSpiImpl());
+
+        byte[] data = new byte[1024];
+        ByteArrayInputStream bais =
+            new ByteArrayInputStream(data);
+
+        reader.setInput(ImageIO.createImageInputStream(bais));
+        IIOMetadata metadata = reader.getImageMetadata(1);
+        if(metadata == null) {
+            throw new RuntimeException("IIOMetada is NULL");
+        }
+
+        String[] formatNames = metadata.getMetadataFormatNames();
+
+        for(int j=0; j<formatNames.length; j++) {
+
+            String formatName = formatNames[j];
+            System.out.println("\nFormat Names : " + formatName);
+
+            try {
+                IIOMetadataFormat metadataFormat =
+                    metadata.getMetadataFormat(formatName);
+                System.out.println("  Class Name " +
+                                   metadataFormat.getClass());
+            } catch(IllegalStateException ise) {
+                Throwable t = ise;
+                t.printStackTrace();
+                while(t.getCause() != null) {
+                    t = t.getCause();
+                    t.printStackTrace();
+                }
+                // test failed!
+                // stop applet!
+                System.out.println("Test faied.");
+                throw new RuntimeException("Test failed.", ise);
+            }
+        }
+    }
+
+    public static class DummyImageReaderImpl extends ImageReader {
+
+        public DummyImageReaderImpl(ImageReaderSpi originatingProvider) {
+            super(originatingProvider);
+        }
+
+        public int getNumImages(boolean allowSearch) throws IOException {
+            return 5;
+        }
+
+        public int getWidth(int imageIndex) throws IOException {
+            if (input == null)
+                throw new IllegalStateException();
+            if (imageIndex >= 5 || imageIndex < 0)
+                throw new IndexOutOfBoundsException();
+
+            return 10;
+        }
+
+        public int getHeight(int imageIndex) throws IOException {
+            if (input == null)
+                throw new IllegalStateException();
+            if (imageIndex >= 5 || imageIndex < 0)
+                throw new IndexOutOfBoundsException();
+
+            return 15;
+        }
+
+        public Iterator getImageTypes(int imageIndex) throws IOException {
+            if (input == null)
+                throw new IllegalStateException();
+            if (imageIndex >= 5 || imageIndex < 0)
+                throw new IndexOutOfBoundsException();
+
+            Vector imageTypes = new Vector();
+            imageTypes.add(ImageTypeSpecifier.createFromBufferedImageType
+                           (BufferedImage.TYPE_BYTE_GRAY ));
+            return imageTypes.iterator();
+        }
+
+        public IIOMetadata getStreamMetadata() throws IOException {
+            return new DummyIIOMetadataImpl(true, null, null, null, null);
+        }
+
+        public IIOMetadata getImageMetadata(int imageIndex) throws IOException {
+
+            if (input == null)
+                throw new IllegalStateException();
+            if (imageIndex >= 5 || imageIndex < 0)
+                throw new IndexOutOfBoundsException();
+            if (seekForwardOnly) {
+                if (imageIndex < minIndex)
+                    throw new IndexOutOfBoundsException();
+                minIndex = imageIndex;
+            }
+            System.out.println("Current format class name " + DummyIIOMetadataFormatImpl.class.getName());
+            return new DummyIIOMetadataImpl(true,
+                                            DummyIIOMetadataFormatImpl.nativeMetadataFormatName,
+                                            DummyIIOMetadataFormatImpl.class.getName(),
+                                            null, null);
+        }
+
+
+        public BufferedImage read(int imageIndex, ImageReadParam param)
+          throws IOException {
+            if (input == null)
+                throw new IllegalStateException();
+            if (imageIndex >= 5 || imageIndex < 0)
+                throw new IndexOutOfBoundsException();
+            if (seekForwardOnly) {
+                if (imageIndex < minIndex)
+                    throw new IndexOutOfBoundsException();
+                minIndex = imageIndex;
+            }
+
+            return getDestination(param, getImageTypes(imageIndex), 10, 15);
+        }
+
+        // protected  methods - now public
+
+        public  boolean abortRequested() {
+            return super.abortRequested();
+        }
+
+        public  void clearAbortRequest() {
+            super.clearAbortRequest();
+        }
+
+        public  void processImageComplete() {
+            super.processImageComplete();
+        }
+
+        public  void processImageProgress(float percentageDone) {
+            super.processImageProgress(percentageDone);
+        }
+
+        public  void processImageStarted(int imageIndex) {
+            super.processImageStarted(imageIndex);
+        }
+
+        public  void processImageUpdate(BufferedImage theImage,
+                                        int minX,
+                                        int minY,
+                                        int width,
+                                        int height,
+                                        int periodX,
+                                        int periodY,
+                                        int[] bands) {
+            super.processImageUpdate(theImage,
+                                     minX,
+                                     minY,
+                                     width,
+                                     height,
+                                     periodX,
+                                     periodY,
+                                     bands);
+        }
+
+        public  void processPassComplete(BufferedImage theImage) {
+            super. processPassComplete(theImage);
+        }
+
+        public  void processPassStarted(BufferedImage theImage,
+                                        int pass, int minPass,
+                                        int maxPass,
+                                        int minX,
+                                        int minY,
+                                        int periodX,
+                                        int periodY,
+                                        int[] bands) {
+            super.processPassStarted(theImage,
+                                     pass,
+                                     minPass,
+                                     maxPass,
+                                     minX,
+                                     minY,
+                                     periodX,
+                                     periodY,
+                                     bands);
+        }
+
+        public  void processReadAborted() {
+            super.processReadAborted();
+        }
+
+        public  void processSequenceComplete() {
+            super.processSequenceComplete();
+        }
+
+        public  void processSequenceStarted(int minIndex) {
+            super.processSequenceStarted(minIndex);
+        }
+
+        public  void processThumbnailComplete() {
+            super.processThumbnailComplete();
+        }
+
+        public  void processThumbnailPassComplete(BufferedImage theThumbnail) {
+            super.processThumbnailPassComplete(theThumbnail);
+        }
+
+        public  void processThumbnailPassStarted(BufferedImage theThumbnail,
+                                                 int pass,
+                                                 int minPass,
+                                                 int maxPass,
+                                                 int minX,
+                                                 int minY,
+                                                 int periodX,
+                                                 int periodY,
+                                                 int[] bands) {
+            super.processThumbnailPassStarted(theThumbnail,
+                                              pass,
+                                              minPass,
+                                              maxPass,
+                                              minX,
+                                              minY,
+                                              periodX,
+                                              periodY,
+                                              bands);
+        }
+
+        public  void processThumbnailProgress(float percentageDone) {
+            super.processThumbnailProgress(percentageDone);
+        }
+
+        public  void processThumbnailStarted(int imageIndex, int thumbnailIndex) {
+            super.processThumbnailStarted(imageIndex, thumbnailIndex);
+        }
+
+        public  void processThumbnailUpdate(BufferedImage theThumbnail,
+                                            int minX,
+                                            int minY,
+                                            int width,
+                                            int height,
+                                            int periodX,
+                                            int periodY,
+                                            int[] bands) {
+            super.processThumbnailUpdate(theThumbnail,
+                                         minX,
+                                         minY,
+                                         width,
+                                         height,
+                                         periodX,
+                                         periodY,
+                                         bands);
+        }
+
+        public  void processWarningOccurred(String warning) {
+            super.processWarningOccurred(warning);
+        }
+
+
+
+        public static Rectangle getSourceRegion(ImageReadParam param,
+                                                int srcWidth,
+                                                int srcHeight) {
+            return ImageReader.getSourceRegion(param, srcWidth, srcHeight);
+        }
+
+        public static void computeRegions(ImageReadParam param,
+                                          int srcWidth,
+                                          int srcHeight,
+                                          BufferedImage image,
+                                          Rectangle srcRegion,
+                                          Rectangle destRegion) {
+            ImageReader.computeRegions(param,
+                                       srcWidth,
+                                       srcHeight,
+                                       image,
+                                       srcRegion,
+                                       destRegion);
+        }
+
+        public static void checkReadParamBandSettings(ImageReadParam param,
+                                                      int numSrcBands,
+                                                      int numDstBands) {
+            ImageReader.checkReadParamBandSettings( param,
+                                                    numSrcBands,
+                                                    numDstBands);
+        }
+
+        public static BufferedImage getDestination(ImageReadParam param,
+                                                   Iterator imageTypes,
+                                                   int width,
+                                                   int height)
+          throws IIOException {
+            return ImageReader.getDestination(param,
+                                              imageTypes,
+                                              width,
+                                              height);
+        }
+
+        public  void setAvailableLocales(Locale[] locales) {
+            if (locales == null || locales.length == 0)
+                availableLocales = null;
+            else
+                availableLocales = (Locale[])locales.clone();
+        }
+
+        public  void processWarningOccurred(String baseName, String keyword) {
+            super.processWarningOccurred(baseName, keyword);
+        }
+    }
+
+    public static class DummyIIOMetadataFormatImpl
+        extends IIOMetadataFormatImpl {
+        public static String nativeMetadataFormatName =
+        "javax_imageio_dummy_1.0";
+
+        private static IIOMetadataFormat instance = null;
+
+
+        private DummyIIOMetadataFormatImpl() {
+            super(DummyIIOMetadataFormatImpl.nativeMetadataFormatName,
+                  CHILD_POLICY_SOME);
+        }
+
+        public boolean canNodeAppear(String elementName,
+                                     ImageTypeSpecifier imageType) {
+            return false;
+        }
+
+        public static synchronized IIOMetadataFormat getInstance() {
+            if (instance == null) {
+                instance = new DummyIIOMetadataFormatImpl();
+            }
+            return instance;
+        }
+    }
+
+    public static class DummyIIOMetadataImpl extends IIOMetadata {
+
+        public DummyIIOMetadataImpl() {
+            super();
+        }
+
+        public DummyIIOMetadataImpl(boolean standardMetadataFormatSupported,
+                                    String nativeMetadataFormatName,
+                                    String nativeMetadataFormatClassName,
+                                    String[] extraMetadataFormatNames,
+                                    String[] extraMetadataFormatClassNames) {
+            super(standardMetadataFormatSupported,
+                  nativeMetadataFormatName,
+                  nativeMetadataFormatClassName,
+                  extraMetadataFormatNames,
+                  extraMetadataFormatClassNames);
+        }
+
+        public boolean isReadOnly() {
+            return true;
+        }
+
+        public Node getAsTree(String formatName) {
+            return null;
+        }
+
+        public void mergeTree(String formatName, Node root)
+          throws IIOInvalidTreeException {
+            throw new IllegalStateException();
+        }
+
+        public void reset() {
+            throw new IllegalStateException();
+        }
+    }
+
+    public static class DummyImageReaderSpiImpl extends ImageReaderSpi {
+
+        static final String[] names ={ "myformat" };
+
+        public DummyImageReaderSpiImpl() {
+            super("vendorName",
+                  "version",
+                  names,
+                  null,
+                  null,
+                  "DummyImageReaderImpl",
+                  STANDARD_INPUT_TYPE,
+                  null,
+                  true,
+                  null,
+                  null,
+                  null,
+                  null,
+                  true,
+                  null,
+                  null,
+                  null,
+                  null);
+        }
+        public boolean canDecodeInput(Object source)
+          throws IOException {
+            return true;
+        }
+        public ImageReader createReaderInstance(Object extension)
+          throws IOException {
+            return new DummyImageReaderImpl(this);
+        }
+        public String getDescription(Locale locale) {
+            return "DummyImageReaderSpiImpl";
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/IIOMetadataFormat/runMetadataFormatTest.sh	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,228 @@
+#!/bin/ksh -p
+#
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+#
+#   @test
+#   @bug        4929170 7078379
+#   @summary    Tests that user-supplied IIOMetadata implementations
+#               loaded by separate classloader is able to load correspnding 
+#               IIOMetadataFormat implementations.
+#   @author     Andrew Brygin
+#
+#   @compile    UserPluginMetadataFormatTest.java MetadataFormatTest.java MetadataTest.java
+#   @run shell/timeout=60 runMetadataFormatTest.sh
+
+# Note!!!! JavaCodeForYourTest_CHANGE_THIS.java must be changed or deleted.  
+# If there is any java code which will be executed during the test, it must 
+# be compiled by the line above.  If multiple .java files, separate the 
+# files by spaces on that line.  See testing page of AWT home page for
+# pointers to the testharness spec. and FAQ.
+# Note!!!! Change AppletDeadlock.sh to the name of your test!!!!
+
+# There are several resources which need to be present before many 
+#  shell scripts can run.  Following are examples of how to check for
+#  many common ones.
+# 
+# Note that the shell used is the Korn Shell, KSH
+#
+# Also note, it is recommended that make files NOT be used.  Rather,
+#  put the individual commands directly into this file.  That way,
+#  it is possible to use command line arguments and other shell tech-
+#  niques to find the compiler, etc on different systems.  For example,
+#  a different path could be used depending on whether this were a
+#  Solaris or Win32 machine, which is more difficult (if even possible)
+#  in a make file.  
+
+
+# Beginning of subroutines:
+status=1
+
+#Call this from anywhere to fail the test with an error message
+# usage: fail "reason why the test failed"
+fail() 
+ { echo "The test failed :-("
+   echo "$*" 1>&2
+   exit 1
+ } #end of fail()
+
+#Call this from anywhere to pass the test with a message
+# usage: pass "reason why the test passed if applicable"
+pass() 
+ { echo "The test passed!!!"
+   echo "$*" 1>&2
+   exit 0
+ } #end of pass()
+
+# end of subroutines
+
+
+# The beginning of the script proper
+
+# Checking for proper OS
+OS=`uname -s`
+case "$OS" in
+   SunOS )
+      VAR="One value for Sun"
+      DEFAULT_JDK=/none
+      #DEFAULT_JDK=/usr/local/java/jdk1.2/solaris
+      FILESEP="/"
+      ;;
+
+   Linux | Darwin  )
+      VAR="A different value for Linux"
+      DEFAULT_JDK=/none
+      #DEFAULT_JDK=/usr/local/java/jdk1.4/linux-i386
+      FILESEP="/"
+      ;;
+
+   Windows_95 | Windows_98 | Windows_NT | Windows_ME )
+      VAR="A different value for Win32"
+      DEFAULT_JDK=/none
+      #DEFAULT_JDK=/usr/local/java/jdk1.2/win32
+      FILESEP="\\"
+      ;;
+
+    CYGWIN* )
+      VAR="A different value for CYGWIN"
+      DEFAULT_JDK=/none
+      FILESEP="/"
+      ;;
+
+   # catch all other OSs
+   * )
+      echo "Unrecognized system!  $OS"
+      fail "Unrecognized system!  $OS"
+      ;;
+esac
+
+# check that some executable or other file you need is available, abort if not
+#  note that the name of the executable is in the fail string as well.
+# this is how to check for presence of the compiler, etc.
+#RESOURCE=`whence SomeProgramOrFileNeeded`
+#if [ "${RESOURCE}" = "" ] ; 
+#   then fail "Need SomeProgramOrFileNeeded to perform the test" ; 
+#fi
+
+# IT'S FINE TO DELETE THIS IF NOT NEEDED!
+# check if an environment variable you need is set, give it a default if not
+#if [ -z "${NEEDED_VAR}" ] ; then
+#   # The var is NOT set, so give it a default
+#   NEEDED_VAR=/some/default/value/such/as/a/path
+#fi
+
+# IT'S FINE TO DELETE THIS IF NOT NEEDED!
+#if [ -z "${NEEDED_LATER_VAR}" ] ; then
+#   # The var is NOT set, so give it a default
+#   # will need it in other scripts called from this one, so export it
+#   NEEDED_LATER_VAR="/a/different/path/note/the/quotes"
+#   export NEEDED_LATER_VAR
+#fi
+
+# Want this test to run standalone as well as in the harness, so do the 
+#  following to copy the test's directory into the harness's scratch directory 
+#  and set all appropriate variables:
+
+if [ -z "${TESTJAVA}" ] ; then
+   # TESTJAVA is not set, so the test is running stand-alone.
+   # TESTJAVA holds the path to the root directory of the build of the JDK
+   # to be tested.  That is, any java files run explicitly in this shell
+   # should use TESTJAVA in the path to the java interpreter.
+   # So, we'll set this to the JDK spec'd on the command line.  If none
+   # is given on the command line, tell the user that and use a cheesy
+   # default.
+   # THIS IS THE JDK BEING TESTED.
+   if [ -n "$1" ] ;
+      then TESTJAVA=$1
+      else echo "no JDK specified on command line so using default!"
+	 TESTJAVA=$DEFAULT_JDK
+   fi
+   TESTSRC=.
+   TESTCLASSES=.
+   STANDALONE=1;
+fi
+echo "JDK under test is: $TESTJAVA"
+
+#Deal with .class files:
+if [ -n "${STANDALONE}" ] ; 
+   then 
+   #if standalone, remind user to cd to dir. containing test before running it
+   echo "Just a reminder: cd to the dir containing this test when running it"
+   # then compile all .java files (if there are any) into .class files
+   if [ -a *.java ] ; 
+      then echo "Reminder, this test should be in its own directory with all"
+      echo "supporting files it needs in the directory with it."
+      ${TESTJAVA}/bin/javac ./*.java ; 
+   fi
+   # else in harness so copy all the class files from where jtreg put them
+   # over to the scratch directory this test is running in. 
+   else cp ${TESTCLASSES}/*.class . ;
+fi
+
+#if in test harness, then copy the entire directory that the test is in over 
+# to the scratch directory.  This catches any support files needed by the test.
+
+#if [ -z "${STANDALONE}" ] ; 
+#   then cp ${TESTSRC}/* . 
+#fi
+
+#Just before executing anything, make sure it has executable permission!
+chmod 777 ./*
+
+###############  YOUR TEST CODE HERE!!!!!!!  #############
+
+#All files required for the test should be in the same directory with
+# this file.  If converting a standalone test to run with the harness,
+# as long as all files are in the same directory and it returns 0 for
+# pass, you should be able to cut and paste it into here and it will
+# run with the test harness.
+
+# This is an example of running something -- test
+# The stuff below catches the exit status of test then passes or fails
+# this shell test as appropriate ( 0 status is considered a pass here )
+#./test # DELETE THIS LINE AND REPLACE WITH YOUR OWN COMMAND!!!
+
+if [ -d ./test_classes ] ; then 
+    rm -rf ./test_calsses
+fi
+
+mkdir ./test_classes
+ 
+# split application classes and test plugin classes
+mv ./UserPluginMetadataFormatTest*.class ./test_classes
+
+$TESTJAVA/bin/java MetadataFormatTest test_classes UserPluginMetadataFormatTest
+
+###############  END YOUR TEST CODE !!!!! ############
+status=$?
+
+# pass or fail the test based on status of the command
+if [ $status -eq "0" ];
+   then pass "Test passed - no stack trace printing"
+
+   else fail "Test failure - stack trace was printed"
+fi
+
+#For additional examples of how to write platform independent KSH scripts,
+# see the jtreg file itself.  It is a KSH script for both Solaris and Win32
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/IIOMetadataFormat/runMetadataFormatThreadTest.sh	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,229 @@
+#!/bin/ksh -p
+#
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+#
+#   @test
+#   @bug        4929170 7078379
+#   @summary    Tests that user-supplied IIOMetadata implementations 
+#                loaded by separate classloader in separate thread  
+#                is able to load correspnding IIOMetadataFormat 
+#                implementations.
+#   @author     Andrew Brygin
+#
+#   @compile    UserPluginMetadataFormatTest.java MetadataFormatThreadTest.java MetadataTest.java
+#   @run shell/timeout=60 runMetadataFormatThreadTest.sh
+
+# Note!!!! JavaCodeForYourTest_CHANGE_THIS.java must be changed or deleted.  
+# If there is any java code which will be executed during the test, it must 
+# be compiled by the line above.  If multiple .java files, separate the 
+# files by spaces on that line.  See testing page of AWT home page for
+# pointers to the testharness spec. and FAQ.
+# Note!!!! Change AppletDeadlock.sh to the name of your test!!!!
+
+# There are several resources which need to be present before many 
+#  shell scripts can run.  Following are examples of how to check for
+#  many common ones.
+# 
+# Note that the shell used is the Korn Shell, KSH
+#
+# Also note, it is recommended that make files NOT be used.  Rather,
+#  put the individual commands directly into this file.  That way,
+#  it is possible to use command line arguments and other shell tech-
+#  niques to find the compiler, etc on different systems.  For example,
+#  a different path could be used depending on whether this were a
+#  Solaris or Win32 machine, which is more difficult (if even possible)
+#  in a make file.  
+
+
+# Beginning of subroutines:
+status=1
+
+#Call this from anywhere to fail the test with an error message
+# usage: fail "reason why the test failed"
+fail() 
+ { echo "The test failed :-("
+   echo "$*" 1>&2
+   exit 1
+ } #end of fail()
+
+#Call this from anywhere to pass the test with a message
+# usage: pass "reason why the test passed if applicable"
+pass() 
+ { echo "The test passed!!!"
+   echo "$*" 1>&2
+   exit 0
+ } #end of pass()
+
+# end of subroutines
+
+
+# The beginning of the script proper
+
+# Checking for proper OS
+OS=`uname -s`
+case "$OS" in
+   SunOS )
+      VAR="One value for Sun"
+      DEFAULT_JDK=/none
+      #DEFAULT_JDK=/usr/local/java/jdk1.2/solaris
+      FILESEP="/"
+      ;;
+
+   Linux | Darwin )
+      VAR="A different value for Linux"
+      DEFAULT_JDK=/none
+      #DEFAULT_JDK=/usr/local/java/jdk1.4/linux-i386
+      FILESEP="/"
+      ;;
+
+   Windows_95 | Windows_98 | Windows_NT | Windows_ME )
+      VAR="A different value for Win32"
+      DEFAULT_JDK=/none
+      #DEFAULT_JDK=/usr/local/java/jdk1.2/win32
+      FILESEP="\\"
+      ;;
+    
+    CYGWIN* )
+      VAR="A different value for CYGWIN"
+      DEFAULT_JDK=/none
+      FILESEP="/"
+      ;;
+
+   # catch all other OSs
+   * )
+      echo "Unrecognized system!  $OS"
+      fail "Unrecognized system!  $OS"
+      ;;
+esac
+
+# check that some executable or other file you need is available, abort if not
+#  note that the name of the executable is in the fail string as well.
+# this is how to check for presence of the compiler, etc.
+#RESOURCE=`whence SomeProgramOrFileNeeded`
+#if [ "${RESOURCE}" = "" ] ; 
+#   then fail "Need SomeProgramOrFileNeeded to perform the test" ; 
+#fi
+
+# IT'S FINE TO DELETE THIS IF NOT NEEDED!
+# check if an environment variable you need is set, give it a default if not
+#if [ -z "${NEEDED_VAR}" ] ; then
+#   # The var is NOT set, so give it a default
+#   NEEDED_VAR=/some/default/value/such/as/a/path
+#fi
+
+# IT'S FINE TO DELETE THIS IF NOT NEEDED!
+#if [ -z "${NEEDED_LATER_VAR}" ] ; then
+#   # The var is NOT set, so give it a default
+#   # will need it in other scripts called from this one, so export it
+#   NEEDED_LATER_VAR="/a/different/path/note/the/quotes"
+#   export NEEDED_LATER_VAR
+#fi
+
+# Want this test to run standalone as well as in the harness, so do the 
+#  following to copy the test's directory into the harness's scratch directory 
+#  and set all appropriate variables:
+
+if [ -z "${TESTJAVA}" ] ; then
+   # TESTJAVA is not set, so the test is running stand-alone.
+   # TESTJAVA holds the path to the root directory of the build of the JDK
+   # to be tested.  That is, any java files run explicitly in this shell
+   # should use TESTJAVA in the path to the java interpreter.
+   # So, we'll set this to the JDK spec'd on the command line.  If none
+   # is given on the command line, tell the user that and use a cheesy
+   # default.
+   # THIS IS THE JDK BEING TESTED.
+   if [ -n "$1" ] ;
+      then TESTJAVA=$1
+      else echo "no JDK specified on command line so using default!"
+	 TESTJAVA=$DEFAULT_JDK
+   fi
+   TESTSRC=.
+   TESTCLASSES=.
+   STANDALONE=1;
+fi
+echo "JDK under test is: $TESTJAVA"
+
+#Deal with .class files:
+if [ -n "${STANDALONE}" ] ; 
+   then 
+   #if standalone, remind user to cd to dir. containing test before running it
+   echo "Just a reminder: cd to the dir containing this test when running it"
+   # then compile all .java files (if there are any) into .class files
+   if [ -a *.java ] ; 
+      then echo "Reminder, this test should be in its own directory with all"
+      echo "supporting files it needs in the directory with it."
+      ${TESTJAVA}/bin/javac ./*.java ; 
+   fi
+   # else in harness so copy all the class files from where jtreg put them
+   # over to the scratch directory this test is running in. 
+   else cp ${TESTCLASSES}/*.class . ;
+fi
+
+#if in test harness, then copy the entire directory that the test is in over 
+# to the scratch directory.  This catches any support files needed by the test.
+
+#if [ -z "${STANDALONE}" ] ; 
+#   then cp ${TESTSRC}/* . 
+#fi
+
+#Just before executing anything, make sure it has executable permission!
+chmod 777 ./*
+
+###############  YOUR TEST CODE HERE!!!!!!!  #############
+
+#All files required for the test should be in the same directory with
+# this file.  If converting a standalone test to run with the harness,
+# as long as all files are in the same directory and it returns 0 for
+# pass, you should be able to cut and paste it into here and it will
+# run with the test harness.
+
+# This is an example of running something -- test
+# The stuff below catches the exit status of test then passes or fails
+# this shell test as appropriate ( 0 status is considered a pass here )
+#./test # DELETE THIS LINE AND REPLACE WITH YOUR OWN COMMAND!!!
+
+if [ -d ./test_classes ] ; then 
+    rm -rf ./test_calsses
+fi
+
+mkdir ./test_classes
+ 
+# split application classes and test plugin classes
+mv ./UserPluginMetadataFormatTest*.class ./test_classes
+
+$TESTJAVA/bin/java MetadataFormatThreadTest test_classes UserPluginMetadataFormatTest
+
+###############  END YOUR TEST CODE !!!!! ############
+status=$?
+
+# pass or fail the test based on status of the command
+if [ $status -eq "0" ];
+   then pass "Test passed - no stack trace printing"
+
+   else fail "Test failure - stack trace was printed"
+fi
+
+#For additional examples of how to write platform independent KSH scripts,
+# see the jtreg file itself.  It is a KSH script for both Solaris and Win32
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/IIOMetadataFormatImplTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 4403350 4403352 4436995 4438977
+ * @run main IIOMetadataFormatImplTest
+ * @summary Tests various methods of IIOMetadataFormatImpl:
+ *
+ * getElement{Min,Max}Children and getAttribute{Min,Max}Value
+ * getAttributeDescription
+ * getAttributeEnumerations
+ */
+
+import javax.imageio.ImageTypeSpecifier;
+import javax.imageio.metadata.IIOMetadataFormat;
+import javax.imageio.metadata.IIOMetadataFormatImpl;
+
+public class IIOMetadataFormatImplTest {
+
+    public static void main(String[] args) {
+        test440335x();
+        test4436995();
+        test4438977();
+    }
+
+    static class IIOMetadataFormatImpl440335x extends IIOMetadataFormatImpl {
+
+        public IIOMetadataFormatImpl440335x() {
+            super("rootNode", 0, 1);
+            addElement("anElement", "rootNode", 20, 200);
+            addAttribute("anElement", "exclusiveAttr",
+                         IIOMetadataFormat.DATATYPE_INTEGER,
+                         true, null,
+                         "50", "500",
+                         false, false);
+            addAttribute("anElement", "minAttr",
+                         IIOMetadataFormat.DATATYPE_INTEGER,
+                         true, null,
+                         "60", "600",
+                         true, false);
+            addAttribute("anElement", "maxAttr",
+                         IIOMetadataFormat.DATATYPE_INTEGER,
+                         true, null,
+                         "70", "700",
+                         false, true);
+            addAttribute("anElement", "minMaxAttr",
+                         IIOMetadataFormat.DATATYPE_INTEGER,
+                         true, null,
+                         "80", "800",
+                         true, true);
+        }
+
+        public boolean canNodeAppear(String nodeName,
+                                     ImageTypeSpecifier imageType) {
+            return true;
+        }
+    }
+
+    private static void test440335x() {
+        IIOMetadataFormat format = new IIOMetadataFormatImpl440335x();
+
+        // Check that correct value is returned
+        if (format.getElementMinChildren("anElement") != 20) {
+            throw new RuntimeException("Error on getElementMinChildren!");
+        }
+        if (format.getElementMaxChildren("anElement") != 200) {
+            throw new RuntimeException("Error on getElementMaxChildren!");
+        }
+
+        // Check that correct value is returned and no exception is thrown
+        try {
+            if (!format.getAttributeMinValue("anElement",
+                                             "exclusiveAttr").equals("50")) {
+                throw new RuntimeException("Error on exclusiveAttr min!");
+            }
+            if (!format.getAttributeMaxValue("anElement",
+                                             "exclusiveAttr").equals("500")) {
+                throw new RuntimeException("Error on exclusiveAttr max!");
+            }
+            if (!format.getAttributeMinValue("anElement",
+                                             "minAttr").equals("60")) {
+                throw new RuntimeException("Error on minAttr min!");
+            }
+            if (!format.getAttributeMaxValue("anElement",
+                                             "minAttr").equals("600")) {
+                throw new RuntimeException("Error on minAttr max!");
+            }
+            if (!format.getAttributeMinValue("anElement",
+                                             "maxAttr").equals("70")) {
+                throw new RuntimeException("Error on maxAttr min!");
+            }
+            if (!format.getAttributeMaxValue("anElement",
+                                             "maxAttr").equals("700")) {
+                throw new RuntimeException("Error on maxAttr max!");
+            }
+            if (!format.getAttributeMinValue("anElement",
+                                             "minMaxAttr").equals("80")) {
+                throw new RuntimeException("Error on minMaxAttr min!");
+            }
+            if (!format.getAttributeMaxValue("anElement",
+                                             "minMaxAttr").equals("800")) {
+                throw new RuntimeException("Error on minMaxAttr max!");
+            }
+        } catch (IllegalStateException e) {
+            throw new RuntimeException("Got IllegalStateException!");
+        }
+    }
+
+    static class IIOMetadataFormatImpl4436995 extends IIOMetadataFormatImpl {
+
+        public IIOMetadataFormatImpl4436995(String root,
+                                            int minChildren, int maxChildren) {
+            super(root, minChildren, maxChildren);
+        }
+
+        public void addAttribute(String elementName,
+                                 String attrName,
+                                 int dataType,
+                                 boolean required,
+                                 int listMinLength, int listMaxLength) {
+            super.addAttribute(elementName,
+                               attrName,
+                               dataType,
+                               required, listMinLength,
+                               listMaxLength);
+        }
+
+        public boolean canNodeAppear(String elementName,
+                                     ImageTypeSpecifier imageType) {
+            return true;
+        }
+    }
+
+    private static void test4436995() {
+        String result;
+
+        IIOMetadataFormatImpl4436995 fmt =
+            new IIOMetadataFormatImpl4436995("root", 1, 10);
+        fmt.addAttribute("root", "attr", fmt.DATATYPE_INTEGER, true, 2, 5);
+        try {
+            result = fmt.getAttributeDescription("root", "non-existent", null);
+            throw new RuntimeException("Failed to get IAE!");
+        } catch(IllegalArgumentException e) {
+        }
+    }
+
+    static class IIOMetadataFormatImpl4438977 extends IIOMetadataFormatImpl {
+
+        public IIOMetadataFormatImpl4438977(String root,
+                                            int minChildren, int maxChildren) {
+            super(root, minChildren, maxChildren);
+        }
+
+        public void addAttribute(String elementName,
+                                 String attrName,
+                                 int dataType,
+                                 boolean required,
+                                 int listMinLength, int listMaxLength) {
+            super.addAttribute(elementName,
+                               attrName,
+                               dataType,
+                               required, listMinLength,
+                               listMaxLength);
+        }
+
+        public boolean canNodeAppear(String elementName,
+                                     ImageTypeSpecifier imageType) {
+            return true;
+        }
+    }
+
+    private static void test4438977() {
+        String[] result;
+
+        IIOMetadataFormatImpl4438977 fmt =
+            new IIOMetadataFormatImpl4438977("root", 1, 10);
+        fmt.addAttribute("root", "attr", fmt.DATATYPE_INTEGER, true, 2, 5);
+        try {
+            result = fmt.getAttributeEnumerations("root", "attr");
+            throw new RuntimeException("Failed to get IAE!");
+        } catch(IllegalArgumentException e) {
+        }
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/MetadataFormatPrinter.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,505 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+//
+
+import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.StringTokenizer;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.metadata.IIOMetadataFormat;
+import javax.imageio.metadata.IIOMetadataFormatImpl;
+import javax.imageio.spi.IIORegistry;
+import javax.imageio.spi.ImageReaderSpi;
+import com.sun.imageio.plugins.png.PNGMetadata;
+
+public class MetadataFormatPrinter {
+
+    private int indentLevel = 0;
+
+    private int column = 0;
+
+    private PrintStream out;
+
+    private static final int maxColumn = 75;
+
+    private static String[] dataTypeNames = {
+        "String", "Boolean", "Integer", "Float", "Double"
+    };
+
+    // "Infinite" values
+    private static String maxInteger = Integer.toString(Integer.MAX_VALUE);
+
+    public MetadataFormatPrinter(PrintStream out) {
+        this.out = out;
+    }
+
+    private void println() {
+        out.println();
+        column = 0;
+    }
+
+    private void println(String s) {
+        out.println(s);
+        column = 0;
+    }
+
+    private void printWrapped(String in, int leftIndent) {
+        StringTokenizer t = new StringTokenizer(in);
+        while (t.hasMoreTokens()) {
+            String s = t.nextToken();
+            int length = s.length();
+            if (column + length > maxColumn) {
+                println();
+                indent();
+                for (int i = 0; i < leftIndent; i++) {
+                    print(" ");
+                }
+            }
+            out.print(s);
+            out.print(" ");
+            column += length + 1;
+        }
+    }
+
+    private void print(String s) {
+        int length = s.length();
+        if (column + length > maxColumn) {
+            println();
+            indent();
+            print("  ");
+        }
+        out.print(s);
+        column += length;
+    }
+
+    private void print(IIOMetadataFormat format) {
+        String rootName = format.getRootName();
+        println("<!DOCTYPE \"" +
+                           rootName +
+                           "\" [");
+        ++indentLevel;
+        print(format, rootName);
+        --indentLevel;
+        print("]>");
+        println();
+        println();
+    }
+
+    private void indent() {
+        for (int i = 0; i < indentLevel; i++) {
+            out.print("  ");
+            column += 2;
+        }
+    }
+
+    private void printElementInfo(IIOMetadataFormat format,
+                                  String elementName) {
+        println();
+        indent();
+        print("<!ELEMENT \"" +
+              elementName +
+              "\"");
+
+        String[] childNames = format.getChildNames(elementName);
+        boolean hasChildren = true;
+        String separator = " "; // symbol to place between children
+        String terminator = ""; // symbol to follow last child
+        String repeater = ""; // "*" if repeating
+
+        switch (format.getChildPolicy(elementName)) {
+        case IIOMetadataFormat.CHILD_POLICY_EMPTY:
+            hasChildren = false;
+            break;
+        case IIOMetadataFormat.CHILD_POLICY_ALL:
+            separator = ", ";
+            break;
+        case IIOMetadataFormat.CHILD_POLICY_SOME:
+            separator = "?, ";
+            terminator = "?";
+            break;
+        case IIOMetadataFormat.CHILD_POLICY_CHOICE:
+            separator = " | ";
+            break;
+        case IIOMetadataFormat.CHILD_POLICY_SEQUENCE:
+            separator = " | ";
+            repeater = "*";
+            break;
+        case IIOMetadataFormat.CHILD_POLICY_REPEAT:
+            repeater = "*";
+            break;
+        default:
+            break;
+        }
+
+        if (hasChildren) {
+            print(" (");
+            for (int i = 0; i < childNames.length - 1; i++) {
+                print(childNames[i] + separator);
+            }
+            print(childNames[childNames.length - 1] + terminator);
+            print(")" + repeater + ">");
+        } else {
+            print(" EMPTY>");
+        }
+        println();
+
+        String description = format.getElementDescription(elementName, null);
+        if (description != null) {
+            ++indentLevel;
+            indent();
+            printWrapped("<!-- " + description + " -->", 5);
+            println();
+            --indentLevel;
+        }
+        if (format.getChildPolicy(elementName) ==
+            IIOMetadataFormat.CHILD_POLICY_REPEAT) {
+            int minChildren = format.getElementMinChildren(elementName);
+            if (minChildren != 0) {
+                indent();
+                println("  <!-- Min children: " +
+                        minChildren +
+                        " -->");
+            }
+            int maxChildren = format.getElementMaxChildren(elementName);
+            if (maxChildren != Integer.MAX_VALUE) {
+                indent();
+                println("  <!-- Max children: " +
+                        maxChildren +
+                        " -->");
+            }
+        }
+    }
+
+    private void printAttributeInfo(IIOMetadataFormat format,
+                                    String elementName,
+                                    String attrName) {
+        indent();
+        print("<!ATTLIST \"" +
+              elementName +
+              "\" \"" +
+              attrName +
+              "\"");
+
+        int attrValueType =
+            format.getAttributeValueType(elementName, attrName);
+        switch (attrValueType) {
+        case IIOMetadataFormat.VALUE_NONE:
+            throw new RuntimeException
+                ("Encountered VALUE_NONE for an attribute!");
+            // break;
+        case IIOMetadataFormat.VALUE_ARBITRARY:
+            print(" #CDATA");
+            break;
+        case IIOMetadataFormat.VALUE_RANGE:
+        case IIOMetadataFormat.VALUE_RANGE_MIN_INCLUSIVE:
+        case IIOMetadataFormat.VALUE_RANGE_MAX_INCLUSIVE:
+        case IIOMetadataFormat.VALUE_RANGE_MIN_MAX_INCLUSIVE:
+            print(" #CDATA");
+            break;
+        case IIOMetadataFormat.VALUE_ENUMERATION:
+            print(" (");
+            String[] attrValues =
+                format.getAttributeEnumerations(elementName, attrName);
+            for (int j = 0; j < attrValues.length - 1; j++) {
+                print("\"" + attrValues[j] + "\" | ");
+            }
+            print("\"" + attrValues[attrValues.length - 1] + "\")");
+            break;
+        case IIOMetadataFormat.VALUE_LIST:
+            print(" #CDATA");
+            break;
+        default:
+            throw new RuntimeException
+                ("Encountered unknown value type for an attribute!");
+            // break;
+        }
+
+        String defaultValue =
+            format.getAttributeDefaultValue(elementName, attrName);
+        if (defaultValue != null) {
+            print(" ");
+            print("\"" + defaultValue + "\"");
+        } else {
+            if (format.isAttributeRequired(elementName, attrName)) {
+                print(" #REQUIRED");
+            } else {
+                print(" #IMPLIED");
+            }
+        }
+        println(">");
+
+        String description = format.getAttributeDescription(elementName,
+                                                            attrName,
+                                                            null);
+        if (description != null) {
+            ++indentLevel;
+            indent();
+            printWrapped("<!-- " + description + " -->", 5);
+            println();
+            --indentLevel;
+        }
+
+        int dataType = format.getAttributeDataType(elementName, attrName);
+
+        switch (attrValueType) {
+        case IIOMetadataFormat.VALUE_ARBITRARY:
+            indent();
+            println("  <!-- Data type: " + dataTypeNames[dataType] + " -->");
+            break;
+
+        case IIOMetadataFormat.VALUE_RANGE:
+        case IIOMetadataFormat.VALUE_RANGE_MIN_INCLUSIVE:
+        case IIOMetadataFormat.VALUE_RANGE_MAX_INCLUSIVE:
+        case IIOMetadataFormat.VALUE_RANGE_MIN_MAX_INCLUSIVE:
+            indent();
+            println("  <!-- Data type: " + dataTypeNames[dataType] + " -->");
+
+            boolean minInclusive =
+                (attrValueType &
+                 IIOMetadataFormat.VALUE_RANGE_MIN_INCLUSIVE_MASK) != 0;
+            boolean maxInclusive =
+                (attrValueType &
+                 IIOMetadataFormat.VALUE_RANGE_MAX_INCLUSIVE_MASK) != 0;
+            indent();
+            println("  <!-- Min value: " +
+                    format.getAttributeMinValue(elementName, attrName) +
+                    " " +
+                    (minInclusive ? "(inclusive)" : "(exclusive)") +
+                    " -->");
+            String maxValue =
+                format.getAttributeMaxValue(elementName, attrName);
+            // Hack: don't print "infinite" max values
+            if (dataType != IIOMetadataFormat.DATATYPE_INTEGER ||
+                !maxValue.equals(maxInteger)) {
+                indent();
+                println("  <!-- Max value: " +
+                        maxValue +
+                        " " +
+                        (maxInclusive ? "(inclusive)" : "(exclusive)") +
+                        " -->");
+            }
+            break;
+
+        case IIOMetadataFormat.VALUE_LIST:
+            indent();
+            println("  <!-- Data type: List of " + dataTypeNames[dataType] + " -->");
+
+            int minLength =
+                format.getAttributeListMinLength(elementName, attrName);
+            if (minLength != 0) {
+                indent();
+                println("  <!-- Min length: " +
+                        minLength +
+                        " -->");
+            }
+            int maxLength =
+                format.getAttributeListMaxLength(elementName, attrName);
+            if (maxLength != Integer.MAX_VALUE) {
+                indent();
+                println("  <!-- Max length: " +
+                        maxLength +
+                        " -->");
+            }
+            break;
+        }
+    }
+
+    private void printObjectInfo(IIOMetadataFormat format,
+                                 String elementName) {
+        int objectType = format.getObjectValueType(elementName);
+        if (objectType == IIOMetadataFormat.VALUE_NONE) {
+            return;
+        }
+
+        Class objectClass = format.getObjectClass(elementName);
+        if (objectClass != null) {
+            indent();
+            if (objectType == IIOMetadataFormat.VALUE_LIST) {
+                println("  <!-- User object: array of " +
+                        objectClass.getName() +
+                        " -->");
+            } else {
+                println("  <!-- User object: " +
+                        objectClass.getName() +
+                        " -->");
+            }
+
+            Object defaultValue = format.getObjectDefaultValue(elementName);
+            if (defaultValue != null) {
+                indent();
+                println("  <!-- Default value: " +
+                        defaultValue.toString() +
+                        " -->");
+            }
+
+            switch (objectType) {
+            case IIOMetadataFormat.VALUE_RANGE:
+                indent();
+                println("  <!-- Min value: " +
+                        format.getObjectMinValue(elementName).toString() +
+                        " -->");
+                indent();
+                println("  <!-- Max value: " +
+                        format.getObjectMaxValue(elementName).toString() +
+                        " -->");
+                break;
+
+            case IIOMetadataFormat.VALUE_ENUMERATION:
+                Object[] enums = format.getObjectEnumerations(elementName);
+                for (int i = 0; i < enums.length; i++) {
+                    indent();
+                    println("  <!-- Enumerated value: " +
+                            enums[i].toString() +
+                            " -->");
+                }
+                break;
+
+            case IIOMetadataFormat.VALUE_LIST:
+                int minLength = format.getObjectArrayMinLength(elementName);
+                if (minLength != 0) {
+                    indent();
+                    println("  <!-- Min length: " +
+                            minLength +
+                            " -->");
+                }
+                int maxLength = format.getObjectArrayMaxLength(elementName);
+                if (maxLength != Integer.MAX_VALUE) {
+                    indent();
+                    println("  <!-- Max length: " +
+                            maxLength +
+                            " -->");
+                }
+                break;
+            }
+        }
+    }
+
+    // Set of elements that have been printed already
+    Set printedElements = new HashSet();
+
+    // Set of elements that have been scheduled to be printed
+    Set scheduledElements = new HashSet();
+
+    private void print(IIOMetadataFormat format,
+                       String elementName) {
+        // Don't print elements more than once
+        if (printedElements.contains(elementName)) {
+            return;
+        }
+        printedElements.add(elementName);
+
+        // Add the unscheduled children of this node to a list,
+        // and mark them as scheduled
+        List children = new ArrayList();
+        String[] childNames = format.getChildNames(elementName);
+        if (childNames != null) {
+            for (int i = 0; i < childNames.length; i++) {
+                String childName = childNames[i];
+                if (!scheduledElements.contains(childName)) {
+                    children.add(childName);
+                    scheduledElements.add(childName);
+                }
+            }
+        }
+
+        printElementInfo(format, elementName);
+        printObjectInfo(format, elementName);
+
+        ++indentLevel;
+        String[] attrNames = format.getAttributeNames(elementName);
+        for (int i = 0; i < attrNames.length; i++) {
+            printAttributeInfo(format, elementName, attrNames[i]);
+        }
+
+        // Recurse on child nodes
+        Iterator iter = children.iterator();
+        while (iter.hasNext()) {
+            print(format, (String)iter.next());
+        }
+        --indentLevel;
+    }
+
+    public static void main(String[] args) {
+        IIOMetadataFormat format = null;
+        if (args.length == 0 || args[0].equals("javax_imageio_1.0")) {
+            format = IIOMetadataFormatImpl.getStandardFormatInstance();
+        } else {
+            IIORegistry registry = IIORegistry.getDefaultInstance();
+            Iterator iter = registry.getServiceProviders(ImageReaderSpi.class,
+                                                         false);
+            while (iter.hasNext()) {
+                ImageReaderSpi spi = (ImageReaderSpi)iter.next();
+                if (args[0].equals
+                    (spi.getNativeStreamMetadataFormatName())) {
+                    System.out.print(spi.getDescription(null));
+                    System.out.println(": native stream format");
+                    format = spi.getStreamMetadataFormat(args[0]);
+                    break;
+                }
+
+                String[] extraStreamFormatNames =
+                    spi.getExtraStreamMetadataFormatNames();
+                if (extraStreamFormatNames != null &&
+                    Arrays.asList(extraStreamFormatNames).
+                    contains(args[0])) {
+                    System.out.print(spi.getDescription(null));
+                    System.out.println(": extra stream format");
+                    format = spi.getStreamMetadataFormat(args[0]);
+                    break;
+                }
+
+                if (args[0].equals
+                    (spi.getNativeImageMetadataFormatName())) {
+                    System.out.print(spi.getDescription(null));
+                    System.out.println(": native image format");
+                    format = spi.getImageMetadataFormat(args[0]);
+                    break;
+                }
+
+                String[] extraImageFormatNames =
+                    spi.getExtraImageMetadataFormatNames();
+                if (extraImageFormatNames != null &&
+                    Arrays.asList(extraImageFormatNames).contains(args[0])) {
+                    System.out.print(spi.getDescription(null));
+                    System.out.println(": extra image format");
+                    format = spi.getImageMetadataFormat(args[0]);
+                    break;
+                }
+            }
+        }
+
+        if (format == null) {
+            System.err.println("Unknown format: " + args[0]);
+            System.exit(0);
+        }
+
+        MetadataFormatPrinter printer = new MetadataFormatPrinter(System.out);
+        printer.print(format);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/ObjectArrayMaxLength.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 4406353
+ * @run main ObjectArrayMaxLength
+ * @summary Tests the getObjectArrayMaxLength method of
+ * IIOMetadataFormatImpl
+ */
+
+import javax.imageio.ImageTypeSpecifier;
+import javax.imageio.metadata.IIOMetadataFormat;
+import javax.imageio.metadata.IIOMetadataFormatImpl;
+
+class MyIIOMetadataFormatImpl extends IIOMetadataFormatImpl {
+
+    MyIIOMetadataFormatImpl() {
+        super("root", CHILD_POLICY_EMPTY);
+        addObjectValue("root", byte.class, 123, 321);
+    }
+
+    public boolean canNodeAppear(String nodeName, ImageTypeSpecifier type) {
+        return true;
+    }
+}
+
+public class ObjectArrayMaxLength {
+
+    public static void main(String[] args) {
+        IIOMetadataFormat f = new MyIIOMetadataFormatImpl();
+        if (f.getObjectArrayMaxLength("root") != 321) {
+            throw new RuntimeException
+                ("Bad value for getObjectArrayMaxLength!");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/RegisteredFormatsTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug      5017991
+ * @summary  This test verifies two things:
+ *            a) we can get MetadataFormat classes for
+ *                each registered metadata format.
+ *            b) all metadata formats for standard plugins
+ *                are registered.
+ * @run main RegisteredFormatsTest
+ */
+
+import javax.imageio.spi.IIORegistry;
+import javax.imageio.spi.ImageReaderSpi;
+import javax.imageio.metadata.IIOMetadataFormat;
+import java.util.Iterator;
+import java.util.Hashtable;
+import java.util.Enumeration;
+
+public class RegisteredFormatsTest {
+
+    private static Hashtable fmts;
+
+    public static void main(String[] args) {
+        fmts = new Hashtable();
+
+        fmts.put("javax_imageio_jpeg_stream_1.0", Boolean.FALSE);
+        fmts.put("javax_imageio_jpeg_image_1.0",  Boolean.FALSE);
+        fmts.put("javax_imageio_png_1.0",         Boolean.FALSE);
+        fmts.put("javax_imageio_bmp_1.0",         Boolean.FALSE);
+        fmts.put("javax_imageio_wbmp_1.0",        Boolean.FALSE);
+        fmts.put("javax_imageio_gif_stream_1.0",  Boolean.FALSE);
+        fmts.put("javax_imageio_gif_image_1.0",   Boolean.FALSE);
+
+        IIORegistry registry = IIORegistry.getDefaultInstance();
+        Iterator iter = registry.getServiceProviders(ImageReaderSpi.class,
+                                                     false);
+        while(iter.hasNext()) {
+            ImageReaderSpi spi = (ImageReaderSpi)iter.next();
+            String fmt_name;
+            fmt_name = spi.getNativeStreamMetadataFormatName();
+            testStreamMetadataFormat(spi, fmt_name);
+
+            fmt_name = spi.getNativeImageMetadataFormatName();
+            testImageMetadataFormat(spi, fmt_name);
+
+            String[] fmt_names;
+            fmt_names = spi.getExtraStreamMetadataFormatNames();
+            for (int i=0; fmt_names != null && i < fmt_names.length; i++) {
+                testStreamMetadataFormat(spi, fmt_names[i]);
+            }
+
+            fmt_names = spi.getExtraImageMetadataFormatNames();
+            for (int i=0; fmt_names != null && i < fmt_names.length; i++) {
+                testImageMetadataFormat(spi, fmt_names[i]);
+            }
+        }
+        Enumeration keys = fmts.keys();
+        while (keys.hasMoreElements()) {
+            String key = (String)keys.nextElement();
+            boolean val = ((Boolean)fmts.get(key)).booleanValue();
+            if (!val) {
+                throw new RuntimeException("Test failed: format " +
+                                           key + "is not registered.");
+            }
+        }
+    }
+
+    private static void testStreamMetadataFormat(ImageReaderSpi spi,
+                                                 String fmt_name) {
+        if (fmt_name == null) {
+            return;
+        }
+        try {
+            testMetadataFormat(spi.getStreamMetadataFormat(fmt_name),
+                               fmt_name);
+        } catch (Exception e) {
+            throw new RuntimeException("Test failed for " + fmt_name,
+                                       e);
+        }
+    }
+
+    private static void testImageMetadataFormat(ImageReaderSpi spi,
+                                                String fmt_name) {
+        if (fmt_name == null) {
+            return;
+        }
+        try {
+            testMetadataFormat(spi.getImageMetadataFormat(fmt_name),
+                               fmt_name);
+        } catch (Exception e) {
+            throw new RuntimeException("Test failed for " + fmt_name,
+                                       e);
+        }
+    }
+    private static void testMetadataFormat(IIOMetadataFormat fmt,
+                                           String fmt_name) {
+        System.out.print(fmt_name + "...");
+        if (fmt != null) {
+            fmts.put(fmt_name, Boolean.TRUE);
+            System.out.println("Ok");
+        } else {
+            throw new RuntimeException("Test failed for " + fmt_name);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/RemoveElement.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 4432628 7186799
+ * @run main RemoveElement
+ * @summary Checks if ImageMetadataFormatImpl.removeElement properly
+ * removes the element from its parent's child list.
+ */
+
+import javax.imageio.metadata.IIOMetadataFormatImpl;
+import javax.imageio.metadata.IIOMetadataFormat;
+import javax.imageio.ImageTypeSpecifier;
+
+public class RemoveElement {
+
+    public static void main(String[] args) {
+        String elem = "elem2";
+        int policy = IIOMetadataFormat.CHILD_POLICY_SOME;
+        MyFormatImpl fmt = new MyFormatImpl("root", 1, 10);
+        fmt.addElement("elem1", "root", policy);
+        fmt.addElement(elem, "root", policy);
+        fmt.removeElement("elem1");
+
+        boolean gotIAE = false;
+        try {
+            fmt.getChildPolicy("elem1");
+        } catch (IllegalArgumentException e) {
+            gotIAE = true;
+        }
+        if (!gotIAE) {
+            throw new RuntimeException("Element is still present!");
+        }
+        String[] chNames = fmt.getChildNames("root");
+        if (chNames.length != 1) {
+            throw new RuntimeException("Root still has more than 1 child!");
+        }
+        if (!elem.equals(chNames[0])) {
+            throw new RuntimeException("Root's remaining child is incorrect!");
+        }
+    }
+
+    static class MyFormatImpl extends IIOMetadataFormatImpl {
+
+        MyFormatImpl(String root, int minChildren, int maxChildren) {
+            super(root, minChildren, maxChildren);
+        }
+
+        public void addElement(String elementName,
+                               String parentName,
+                               int childPolicy) {
+            super.addElement(elementName, parentName, childPolicy);
+        }
+
+        public void removeElement(String elementName) {
+            super.removeElement(elementName);
+        }
+
+        public boolean canNodeAppear(String elementName,
+                                     ImageTypeSpecifier imageType) {
+            return true;
+        }
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/imageio/metadata/SetAttributeNode.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,175 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 4507256
+ * @run main SetAttributeNode
+ * @summary Tests the functionality of IIOMetadataNode.setAttributeNode().
+ * Four separate tests are involved:
+ *   1) Tests whether a DOMException.INUSE_ATTRIBUTE_ERR is thrown if newAttr
+ *      is already an attribute of another Element object.
+ *   2) Tests whether setAttributeNode() returns the old attribute if it is
+ *      replaced.
+ *   3) Tests whether setAttributeNode() returns null if the new attribute is
+ *      not replacing an existing attribute.
+ *   4) Tests whether the new attribute successfully replaces an existing one.
+ */
+
+import javax.imageio.metadata.IIOMetadataNode;
+import org.w3c.dom.Attr;
+import org.w3c.dom.DOMException;
+import org.w3c.dom.Element;
+import org.w3c.dom.TypeInfo;
+
+public class SetAttributeNode {
+
+    public static void test1() {
+        IIOMetadataNode parent = new IIOMetadataNode("parent");
+        IIOMetadataNode elem   = new IIOMetadataNode("elem");
+
+        MyAttrNode attrNode = new MyAttrNode("name", "value");
+        elem.setAttributeNode(attrNode);
+        attrNode.setOwnerElement(elem);
+
+        try {
+            parent.setAttributeNode(attrNode);
+        } catch (DOMException e) {
+            if (e.code != DOMException.INUSE_ATTRIBUTE_ERR) {
+                throw new RuntimeException("Test 1 failed: " +
+                                           "Invalid exception code: " +
+                                           e.code);
+            }
+            return;
+        }
+
+        throw new RuntimeException("Test 1 failed: DOMException not thrown");
+    }
+
+    public static void test2() {
+        String name = "attr";
+        String oldValue = "old value";
+        String newValue = "new value";
+        Attr retAttr;
+
+        IIOMetadataNode parent = new IIOMetadataNode("parent");
+        MyAttrNode attrNode1 = new MyAttrNode(name, oldValue);
+        MyAttrNode attrNode2 = new MyAttrNode(name, newValue);
+
+        retAttr = parent.setAttributeNode(attrNode1);
+        retAttr = parent.setAttributeNode(attrNode2);
+
+        String actName = retAttr.getNodeName();
+        String actValue = retAttr.getValue();
+
+        if (!actName.equals(name) || !actValue.equals(oldValue)) {
+            throw new RuntimeException("Test 2 failed: Invalid attribute " +
+                                       "returned: " +
+                                       "(name: " + actName +
+                                       ", value: " + actValue + ")");
+        }
+    }
+
+    public static void test3() {
+        IIOMetadataNode parent = new IIOMetadataNode("parent");
+        MyAttrNode attrNode = new MyAttrNode("name", "value");
+        Attr retAttr = parent.setAttributeNode(attrNode);
+
+        if (retAttr != null) {
+            throw new RuntimeException("Test 3 failed: Return value is " +
+                                       "non-null");
+        }
+    }
+
+    public static void test4() {
+        String name = "name";
+        String correctValue = "correct value";
+        String wrongValue = "wrong value";
+
+        IIOMetadataNode parent = new IIOMetadataNode("parent");
+        MyAttrNode attrNode1 = new MyAttrNode(name, wrongValue);
+        MyAttrNode attrNode2 = new MyAttrNode(name, correctValue);
+
+        parent.setAttributeNode(attrNode1);
+        parent.setAttributeNode(attrNode2);
+
+        Attr actAttr = parent.getAttributeNode(name);
+        String actValue = actAttr.getValue();
+
+        if (!actValue.equals(correctValue)) {
+            throw new RuntimeException("Test 4 failed: Return value is: " +
+                                       actValue);
+        }
+    }
+
+    public static void main(String[] args) {
+        test1();
+        test2();
+        test3();
+        test4();
+    }
+}
+
+class MyAttrNode extends IIOMetadataNode implements Attr {
+
+    private Element owner;
+    private String name;
+    private String value;
+
+    public MyAttrNode(String name, String value) {
+        this.name = name;
+        this.value = value;
+    }
+
+    public Element getOwnerElement() {
+        return owner;
+    }
+
+    public void setOwnerElement(Element owner) {
+        this.owner = owner;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public String getValue() {
+        return value;
+    }
+
+    public void setValue(String value) {
+        this.value = value;
+    }
+
+    public boolean getSpecified() {
+        return false;
+    }
+
+    public TypeInfo getSchemaTypeInfo() {
+        return null;
+    }
+
+    public boolean isId() {
+        return false;
+    }
+}
--- a/test/javax/management/remote/mandatory/notif/ListenerScaleTest.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/javax/management/remote/mandatory/notif/ListenerScaleTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -45,7 +45,7 @@
  *
  * As usual with timing-sensitive tests, we could potentially get
  * sporadic failures.  We fail if the ratio of the time with many
- * MBeans to the time with just one MBean is more than 100.  With the
+ * MBeans to the time with just one MBean is more than 500.  With the
  * fix in place, it is usually less than 1, presumably because some
  * code was being interpreted during the first measurement but had
  * been compiled by the second.
@@ -176,7 +176,7 @@
         long manyMBeansTime = timeNotif(mbs);
         System.out.println("Time with many MBeans: " + manyMBeansTime + "ns");
         double ratio = (double) manyMBeansTime / singleMBeanTime;
-        if (ratio > 100.0)
+        if (ratio > 500.0)
             throw new Exception("Failed: ratio=" + ratio);
         System.out.println("Test passed: ratio=" + ratio);
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/swing/JMenuItem/6438430/bug6438430.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 6438430
+ * @summary Tests that submenu title doesn't overlap with submenu indicator
+ *          in JPopupMenu
+ * @author Mikhail Lapshin
+ * @run main/othervm -Dswing.defaultlaf=javax.swing.plaf.metal.MetalLookAndFeel bug6438430
+ * @run main/othervm -Dswing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel bug6438430
+ */
+
+import javax.swing.JMenuItem;
+import javax.swing.JMenu;
+import javax.swing.JCheckBoxMenuItem;
+
+public class bug6438430 {
+    public static void main(String[] args) {
+        JMenu subMenu1 = new JMenu("Long-titled Sub Menu");
+        subMenu1.add(new JMenuItem("SubMenu Item"));
+        JMenuItem checkBoxMenuItem1 = new JCheckBoxMenuItem("CheckBox");
+
+        JMenu menu1 = new JMenu("It works always");
+        menu1.add(checkBoxMenuItem1);
+        menu1.add(subMenu1);
+
+        // Simulate DefaultMenuLayout calls.
+        // The latest traversed menu item must be the widest.
+        checkBoxMenuItem1.getPreferredSize();
+        int width1 = subMenu1.getPreferredSize().width;
+        System.out.println("width1 = " + width1);
+
+
+        JMenu subMenu2 = new JMenu("Long-titled Sub Menu");
+        subMenu2.add(new JMenuItem("SubMenu Item"));
+        JMenuItem checkBoxMenuItem2 = new JCheckBoxMenuItem("CheckBox");
+
+        JMenu menu2 = new JMenu("It did not work before the fix");
+        menu2.add(subMenu2);
+        menu2.add(checkBoxMenuItem2);
+
+        // Simulate DefaultMenuLayout calls.
+        // The latest traversed menu item must be the widest.
+        subMenu2.getPreferredSize();
+        int width2 = checkBoxMenuItem2.getPreferredSize().width;
+        System.out.println("width2 = " + width2);
+
+        if (width1 != width2) {
+            throw new RuntimeException( "Submenu title and submenu indicator " +
+                                        "overlap on JMenuItem!" );
+        }
+
+        System.out.println("Test passed");
+    }
+}
--- a/test/sun/misc/URLClassPath/ClassnameCharTest.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/misc/URLClassPath/ClassnameCharTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -21,75 +21,97 @@
  * questions.
  */
 
-/**
- * See ClassnameCharTest.sh for details.
+/* @test
+ * @bug 4957669 5017871
+ * @compile -XDignore.symbol.file=true ClassnameCharTest.java
+ * @run main ClassnameCharTest
+ * @summary cannot load class names containing some JSR 202 characters;
+ *          plugin does not escape unicode character in http request
  */
 
 import java.io.*;
 import java.net.*;
-import java.security.*;
+import java.util.jar.*;
+import com.sun.net.httpserver.*;
 import sun.applet.AppletClassLoader;
 
-public class ClassnameCharTest implements HttpCallback {
-    private static String FNPrefix;
-    private String[] respBody = new String[52];
-    private byte[][] bufs = new byte[52][8*1024];
-    private static MessageDigest md5;
-    private static byte[] file1Mac, file2Mac;
-    public void request (HttpTransaction req) {
-        try {
-            String filename = req.getRequestURI().getPath();
-            System.out.println("getRequestURI = "+req.getRequestURI());
-            System.out.println("filename = "+filename);
-            FileInputStream fis = new FileInputStream(FNPrefix+filename);
-            req.setResponseEntityBody(fis);
-            req.sendResponse(200, "OK");
-            req.orderlyClose();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
+public class ClassnameCharTest {
+    static String FNPrefix = System.getProperty("test.src", ".") + File.separator;
+    static File classesJar = new File(FNPrefix + "testclasses.jar");
     static HttpServer server;
 
-    public static void test () throws Exception {
+    public static void realMain(String[] args) throws Exception {
+        server = HttpServer.create(new InetSocketAddress(0), 0);
+        server.createContext("/", new HttpHandler() {
+            @Override
+            public void handle(HttpExchange exchange) {
+                try {
+                    String filename = exchange.getRequestURI().getPath();
+                    System.out.println("getRequestURI = " + exchange.getRequestURI());
+                    System.out.println("filename = " + filename);
+                    try (FileInputStream fis = new FileInputStream(classesJar);
+                         JarInputStream jis = new JarInputStream(fis)) {
+                        JarEntry entry;
+                        while ((entry = jis.getNextJarEntry()) != null) {
+                            if (filename.endsWith(entry.getName())) {
+                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                                byte[] buf = new byte[8092];
+                                int count = 0;
+                                while ((count = jis.read(buf)) != -1)
+                                    baos.write(buf, 0, count);
+                                exchange.sendResponseHeaders(200, baos.size());
+                                try (OutputStream os = exchange.getResponseBody()) {
+                                    baos.writeTo(os);
+                                }
+                                return;
+                            }
+                        }
+                        fail("Failed to find " + filename);
+                    }
+                } catch (IOException e) {
+                    unexpected(e);
+                }
+            }
+        });
+        server.start();
         try {
-
-            FNPrefix = System.getProperty("test.classes", ".")+"/";
-            server = new HttpServer (new ClassnameCharTest(), 1, 10, 0);
-            System.out.println ("Server: listening on port: " + server.getLocalPort());
-            URL base = new URL("http://localhost:"+server.getLocalPort());
+            URL base = new URL("http://localhost:" + server.getAddress().getPort());
+            System.out.println ("Server: listening on " + base);
             MyAppletClassLoader acl = new MyAppletClassLoader(base);
-            Class class1 = acl.findClass("fo o");
-            System.out.println("class1 = "+class1);
+            Class<?> class1 = acl.findClass("fo o");
+            System.out.println("class1 = " + class1);
+            pass();
             // can't test the following class unless platform in unicode locale
             // Class class2 = acl.findClass("\u624b\u518c");
             // System.out.println("class2 = "+class2);
-        } catch (Exception e) {
-            if (server != null) {
-                server.terminate();
-            }
-            throw e;
+        } finally {
+            server.stop(0);
+        }
+    }
+
+    static class MyAppletClassLoader extends AppletClassLoader {
+        MyAppletClassLoader(URL base) {
+            super(base);
         }
 
-        server.terminate();
-    }
-
-    public static void main(String[] args) throws Exception {
-        test();
+        @Override
+        public Class<?> findClass(String name) throws ClassNotFoundException {
+            return super.findClass(name);
+        }
     }
 
-    public static void except (String s) {
-        server.terminate();
-        throw new RuntimeException (s);
-    }
+    //--------------------- Infrastructure ---------------------------
+    static volatile int passed = 0, failed = 0;
+    static boolean pass() {passed++; return true;}
+    static boolean fail() {failed++; server.stop(0); Thread.dumpStack(); return false;}
+    static boolean fail(String msg) {System.out.println(msg); return fail();}
+    static void unexpected(Throwable t) {failed++; server.stop(0); t.printStackTrace();}
+    static boolean check(boolean cond) {if (cond) pass(); else fail(); return cond;}
+    static boolean equal(Object x, Object y) {
+        if (x == null ? y == null : x.equals(y)) return pass();
+        else return fail(x + " not equal to " + y);}
+    public static void main(String[] args) throws Throwable {
+        try {realMain(args);} catch (Throwable t) {unexpected(t);}
+        System.out.println("\nPassed = " + passed + " failed = " + failed);
+        if (failed > 0) throw new AssertionError("Some tests failed");}
 }
-
-class MyAppletClassLoader extends AppletClassLoader {
-    MyAppletClassLoader(URL base) {
-        super(base);
-    }
-
-    public Class findClass(String name) throws ClassNotFoundException {
-        return super.findClass(name);
-    }
-}
--- a/test/sun/misc/URLClassPath/ClassnameCharTest.sh	Fri Sep 21 12:22:52 2012 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,60 +0,0 @@
-#! /bin/sh
-
-#
-# 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
-# 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
-# @author Yingxian Wang
-# @bug 4957669 5017871
-# @library ../../../sun/net/www/httptest/
-# @build HttpCallback HttpServer ClosedChannelList HttpTransaction
-# @run shell/timeout=300 ClassnameCharTest.sh
-# @summary ; cannot load class names containing some JSR 202 characters;
-#          plugin does not escape unicode character in http request
-#
-# set platform-dependent variables
-
-OS=`uname -s`
-case "$OS" in
-  SunOS | Linux | Darwin )
-    PS=":"
-    FS="/"
-    ;;
-  Windows* | CYGWIN* )
-    PS=";"
-    FS="\\"
-    ;;
-  * )
-    echo "Unrecognized system!"
-    exit 1;
-    ;;
-esac
-
-cp ${TESTSRC}${FS}testclasses.jar ${TESTCLASSES}
-cd ${TESTCLASSES}
-${TESTJAVA}${FS}bin${FS}jar xvf testclasses.jar "fo o.class"
-${TESTJAVA}${FS}bin${FS}javac -d ${TESTCLASSES} ${TESTSRC}${FS}ClassnameCharTest.java
-
-${TESTJAVA}${FS}bin${FS}java -classpath "${TESTCLASSES}${PS}${TESTCLASSES}${FS}sun${FS}misc${FS}URLClassPath" ClassnameCharTest
-
-rm -rf "fo o.class" testclasses.jar
--- a/test/sun/net/www/AuthHeaderTest.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/net/www/AuthHeaderTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 4804309
  * @library ../../../sun/net/www/httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
+ * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main AuthHeaderTest
  * @summary AuthHeaderTest bug
  */
@@ -90,13 +90,13 @@
         is.close();
     }
 
-    static HttpServer server;
+    static TestHttpServer server;
 
     public static void main (String[] args) throws Exception {
         MyAuthenticator auth = new MyAuthenticator ();
         Authenticator.setDefault (auth);
         try {
-            server = new HttpServer (new AuthHeaderTest(), 1, 10, 0);
+            server = new TestHttpServer (new AuthHeaderTest(), 1, 10, 0);
             System.out.println ("Server: listening on port: " + server.getLocalPort());
             client ("http://localhost:"+server.getLocalPort()+"/d1/foo.html");
         } catch (Exception e) {
--- a/test/sun/net/www/http/ChunkedInputStream/ChunkedEncodingWithProgressMonitorTest.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/net/www/http/ChunkedInputStream/ChunkedEncodingWithProgressMonitorTest.java	Wed Sep 26 22:22:51 2012 -0700
@@ -24,8 +24,6 @@
 /**
  * @test
  * @bug 4333920 4994372
- * @library ../../../../../sun/net/www/httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
  * @run main ChunkedEncodingWithProgressMonitorTest
  * @summary ChunkedEncoding unit test; MeteredStream/ProgressData problem
  */
--- a/test/sun/net/www/http/KeepAliveCache/B5045306.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/net/www/http/KeepAliveCache/B5045306.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 5045306 6356004 6993490
  * @library ../../httptest/
- * @build HttpCallback HttpServer HttpTransaction
+ * @build HttpCallback TestHttpServer HttpTransaction
  * @run main/othervm B5045306
  * @summary Http keep-alive implementation is not efficient
  */
@@ -50,7 +50,7 @@
 public class B5045306
 {
     static SimpleHttpTransaction httpTrans;
-    static HttpServer server;
+    static TestHttpServer server;
 
     public static void main(String[] args) throws Exception {
         startHttpServer();
@@ -60,7 +60,7 @@
     public static void startHttpServer() {
         try {
             httpTrans = new SimpleHttpTransaction();
-            server = new HttpServer(httpTrans, 1, 10, 0);
+            server = new TestHttpServer(httpTrans, 1, 10, 0);
         } catch (IOException e) {
             e.printStackTrace();
         }
--- a/test/sun/net/www/httptest/HttpServer.java	Fri Sep 21 12:22:52 2012 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,728 +0,0 @@
-/*
- * 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
- * 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.net.*;
-import java.io.*;
-import java.nio.*;
-import java.nio.channels.*;
-import sun.net.www.MessageHeader;
-import java.util.*;
-
-/**
- * This class implements a simple HTTP server. It uses multiple threads to
- * handle connections in parallel, and also multiple connections/requests
- * can be handled per thread.
- * <p>
- * It must be instantiated with a {@link HttpCallback} object to which
- * requests are given and must be handled.
- * <p>
- * Simple synchronization between the client(s) and server can be done
- * using the {@link #waitForCondition(String)}, {@link #setCondition(String)} and
- * {@link #rendezvous(String,int)} methods.
- *
- * NOTE NOTE NOTE NOTE NOTE NOTE NOTE
- *
- * If changes are made here, please sure they are propagated to
- * the HTTPS equivalent in the JSSE regression test suite.
- *
- * NOTE NOTE NOTE NOTE NOTE NOTE NOTE
- */
-
-public class HttpServer {
-
-    ServerSocketChannel schan;
-    int threads;
-    int cperthread;
-    HttpCallback cb;
-    Server[] servers;
-
-    /**
-     * Create a <code>HttpServer<code> instance with the specified callback object
-     * for handling requests. One thread is created to handle requests,
-     * and up to ten TCP connections will be handled simultaneously.
-     * @param cb the callback object which is invoked to handle each
-     *  incoming request
-     */
-
-    public HttpServer (HttpCallback cb) throws IOException {
-        this (cb, 1, 10, 0);
-    }
-
-    /**
-     * Create a <code>HttpServer<code> instance with the specified number of
-     * threads and maximum number of connections per thread. This functions
-     * the same as the 4 arg constructor, where the port argument is set to zero.
-     * @param cb the callback object which is invoked to handle each
-     *     incoming request
-     * @param threads the number of threads to create to handle requests
-     *     in parallel
-     * @param cperthread the number of simultaneous TCP connections to
-     *     handle per thread
-     */
-
-    public HttpServer (HttpCallback cb, int threads, int cperthread)
-        throws IOException {
-        this (cb, threads, cperthread, 0);
-    }
-
-    /**
-     * Create a <code>HttpServer<code> instance with the specified number
-     * of threads and maximum number of connections per thread and running on
-     * the specified port. The specified number of threads are created to
-     * handle incoming requests, and each thread is allowed
-     * to handle a number of simultaneous TCP connections.
-     * @param cb the callback object which is invoked to handle
-     *  each incoming request
-     * @param threads the number of threads to create to handle
-     *  requests in parallel
-     * @param cperthread the number of simultaneous TCP connections
-     *  to handle per thread
-     * @param port the port number to bind the server to. <code>Zero</code>
-     *  means choose any free port.
-     */
-
-    public HttpServer (HttpCallback cb, int threads, int cperthread, int port)
-        throws IOException {
-        schan = ServerSocketChannel.open ();
-        InetSocketAddress addr = new InetSocketAddress (port);
-        schan.socket().bind (addr);
-        this.threads = threads;
-        this.cb = cb;
-        this.cperthread = cperthread;
-        servers = new Server [threads];
-        for (int i=0; i<threads; i++) {
-            servers[i] = new Server (cb, schan, cperthread);
-            servers[i].start();
-        }
-    }
-
-    /** Tell all threads in the server to exit within 5 seconds.
-     *  This is an abortive termination. Just prior to the thread exiting
-     *  all channels in that thread waiting to be closed are forceably closed.
-     */
-
-    public void terminate () {
-        for (int i=0; i<threads; i++) {
-            servers[i].terminate ();
-        }
-    }
-
-    /**
-     * return the local port number to which the server is bound.
-     * @return the local port number
-     */
-
-    public int getLocalPort () {
-        return schan.socket().getLocalPort ();
-    }
-
-    static class Server extends Thread {
-
-        ServerSocketChannel schan;
-        Selector selector;
-        SelectionKey listenerKey;
-        SelectionKey key; /* the current key being processed */
-        HttpCallback cb;
-        ByteBuffer consumeBuffer;
-        int maxconn;
-        int nconn;
-        ClosedChannelList clist;
-        boolean shutdown;
-
-        Server (HttpCallback cb, ServerSocketChannel schan, int maxconn) {
-            this.schan = schan;
-            this.maxconn = maxconn;
-            this.cb = cb;
-            nconn = 0;
-            consumeBuffer = ByteBuffer.allocate (512);
-            clist = new ClosedChannelList ();
-            try {
-                selector = Selector.open ();
-                schan.configureBlocking (false);
-                listenerKey = schan.register (selector, SelectionKey.OP_ACCEPT);
-            } catch (IOException e) {
-                System.err.println ("Server could not start: " + e);
-            }
-        }
-
-        /* Stop the thread as soon as possible */
-        public synchronized void terminate () {
-            shutdown = true;
-        }
-
-        public void run ()  {
-            try {
-                while (true) {
-                    selector.select (1000);
-                    Set selected = selector.selectedKeys();
-                    Iterator iter = selected.iterator();
-                    while (iter.hasNext()) {
-                        key = (SelectionKey)iter.next();
-                        if (key.equals (listenerKey)) {
-                            SocketChannel sock = schan.accept ();
-                            if (sock == null) {
-                                /* false notification */
-                                iter.remove();
-                                continue;
-                            }
-                            sock.configureBlocking (false);
-                            sock.register (selector, SelectionKey.OP_READ);
-                            nconn ++;
-                            System.out.println("SERVER: new connection. chan[" + sock + "]");
-                            if (nconn == maxconn) {
-                                /* deregister */
-                                listenerKey.cancel ();
-                                listenerKey = null;
-                            }
-                        } else {
-                            if (key.isReadable()) {
-                                boolean closed;
-                                SocketChannel chan = (SocketChannel) key.channel();
-                                System.out.println("SERVER: connection readable. chan[" + chan + "]");
-                                if (key.attachment() != null) {
-                                    System.out.println("Server: comsume");
-                                    closed = consume (chan);
-                                } else {
-                                    closed = read (chan, key);
-                                }
-                                if (closed) {
-                                    chan.close ();
-                                    key.cancel ();
-                                    if (nconn == maxconn) {
-                                        listenerKey = schan.register (selector, SelectionKey.OP_ACCEPT);
-                                    }
-                                    nconn --;
-                                }
-                            }
-                        }
-                        iter.remove();
-                    }
-                    clist.check();
-                    if (shutdown) {
-                        clist.terminate ();
-                        return;
-                    }
-                }
-            } catch (IOException e) {
-                System.out.println ("Server exception: " + e);
-                // TODO finish
-            }
-        }
-
-        /* read all the data off the channel without looking at it
-             * return true if connection closed
-             */
-        boolean consume (SocketChannel chan) {
-            try {
-                consumeBuffer.clear ();
-                int c = chan.read (consumeBuffer);
-                if (c == -1)
-                    return true;
-            } catch (IOException e) {
-                return true;
-            }
-            return false;
-        }
-
-        /* return true if the connection is closed, false otherwise */
-
-        private boolean read (SocketChannel chan, SelectionKey key) {
-            HttpTransaction msg;
-            boolean res;
-            try {
-                InputStream is = new BufferedInputStream (new NioInputStream (chan));
-                String requestline = readLine (is);
-                MessageHeader mhead = new MessageHeader (is);
-                String clen = mhead.findValue ("Content-Length");
-                String trferenc = mhead.findValue ("Transfer-Encoding");
-                String data = null;
-                if (trferenc != null && trferenc.equals ("chunked"))
-                    data = new String (readChunkedData (is));
-                else if (clen != null)
-                    data = new String (readNormalData (is, Integer.parseInt (clen)));
-                String[] req = requestline.split (" ");
-                if (req.length < 2) {
-                    /* invalid request line */
-                    return false;
-                }
-                String cmd = req[0];
-                URI uri = null;
-                try {
-                    uri = new URI (req[1]);
-                    msg = new HttpTransaction (this, cmd, uri, mhead, data, null, key);
-                    cb.request (msg);
-                } catch (URISyntaxException e) {
-                    System.err.println ("Invalid URI: " + e);
-                    msg = new HttpTransaction (this, cmd, null, null, null, null, key);
-                    msg.sendResponse (501, "Whatever");
-                }
-                res = false;
-            } catch (IOException e) {
-                res = true;
-            }
-            return res;
-        }
-
-        byte[] readNormalData (InputStream is, int len) throws IOException {
-            byte [] buf  = new byte [len];
-            int c, off=0, remain=len;
-            while (remain > 0 && ((c=is.read (buf, off, remain))>0)) {
-                remain -= c;
-                off += c;
-            }
-            return buf;
-        }
-
-        private void readCRLF(InputStream is) throws IOException {
-            int cr = is.read();
-            int lf = is.read();
-
-            if (((cr & 0xff) != 0x0d) ||
-                ((lf & 0xff) != 0x0a)) {
-                throw new IOException(
-                    "Expected <CR><LF>:  got '" + cr + "/" + lf + "'");
-            }
-        }
-
-        byte[] readChunkedData (InputStream is) throws IOException {
-            LinkedList l = new LinkedList ();
-            int total = 0;
-            for (int len=readChunkLen(is); len!=0; len=readChunkLen(is)) {
-                l.add (readNormalData(is, len));
-                total += len;
-                readCRLF(is);  // CRLF at end of chunk
-            }
-            readCRLF(is); // CRLF at end of Chunked Stream.
-            byte[] buf = new byte [total];
-            Iterator i = l.iterator();
-            int x = 0;
-            while (i.hasNext()) {
-                byte[] b = (byte[])i.next();
-                System.arraycopy (b, 0, buf, x, b.length);
-                x += b.length;
-            }
-            return buf;
-        }
-
-        private int readChunkLen (InputStream is) throws IOException {
-            int c, len=0;
-            boolean done=false, readCR=false;
-            while (!done) {
-                c = is.read ();
-                if (c == '\n' && readCR) {
-                    done = true;
-                } else {
-                    if (c == '\r' && !readCR) {
-                        readCR = true;
-                    } else {
-                        int x=0;
-                        if (c >= 'a' && c <= 'f') {
-                            x = c - 'a' + 10;
-                        } else if (c >= 'A' && c <= 'F') {
-                            x = c - 'A' + 10;
-                        } else if (c >= '0' && c <= '9') {
-                            x = c - '0';
-                        }
-                        len = len * 16 + x;
-                    }
-                }
-            }
-            return len;
-        }
-
-        private String readLine (InputStream is) throws IOException {
-            boolean done=false, readCR=false;
-            byte[] b = new byte [512];
-            int c, l = 0;
-
-            while (!done) {
-                c = is.read ();
-                if (c == '\n' && readCR) {
-                    done = true;
-                } else {
-                    if (c == '\r' && !readCR) {
-                        readCR = true;
-                    } else {
-                        b[l++] = (byte)c;
-                    }
-                }
-            }
-            return new String (b);
-        }
-
-        /** close the channel associated with the current key by:
-         * 1. shutdownOutput (send a FIN)
-         * 2. mark the key so that incoming data is to be consumed and discarded
-         * 3. After a period, close the socket
-         */
-
-        synchronized void orderlyCloseChannel (SelectionKey key) throws IOException {
-            SocketChannel ch = (SocketChannel)key.channel ();
-            System.out.println("SERVER: orderlyCloseChannel chan[" + ch + "]");
-            ch.socket().shutdownOutput();
-            key.attach (this);
-            clist.add (key);
-        }
-
-        synchronized void abortiveCloseChannel (SelectionKey key) throws IOException {
-            SocketChannel ch = (SocketChannel)key.channel ();
-            System.out.println("SERVER: abortiveCloseChannel chan[" + ch + "]");
-
-            Socket s = ch.socket ();
-            s.setSoLinger (true, 0);
-            ch.close();
-        }
-    }
-
-
-    /**
-     * Implements blocking reading semantics on top of a non-blocking channel
-     */
-
-    static class NioInputStream extends InputStream {
-        SocketChannel channel;
-        Selector selector;
-        ByteBuffer chanbuf;
-        SelectionKey key;
-        int available;
-        byte[] one;
-        boolean closed;
-        ByteBuffer markBuf; /* reads may be satisifed from this buffer */
-        boolean marked;
-        boolean reset;
-        int readlimit;
-
-        public NioInputStream (SocketChannel chan) throws IOException {
-            this.channel = chan;
-            selector = Selector.open();
-            chanbuf = ByteBuffer.allocate (1024);
-            key = chan.register (selector, SelectionKey.OP_READ);
-            available = 0;
-            one = new byte[1];
-            closed = marked = reset = false;
-        }
-
-        public synchronized int read (byte[] b) throws IOException {
-            return read (b, 0, b.length);
-        }
-
-        public synchronized int read () throws IOException {
-            return read (one, 0, 1);
-        }
-
-        public synchronized int read (byte[] b, int off, int srclen) throws IOException {
-
-            int canreturn, willreturn;
-
-            if (closed)
-                return -1;
-
-            if (reset) { /* satisfy from markBuf */
-                canreturn = markBuf.remaining ();
-                willreturn = canreturn>srclen ? srclen : canreturn;
-                markBuf.get(b, off, willreturn);
-                if (canreturn == willreturn) {
-                    reset = false;
-                }
-            } else { /* satisfy from channel */
-                canreturn = available();
-                if (canreturn == 0) {
-                    block ();
-                    canreturn = available();
-                }
-                willreturn = canreturn>srclen ? srclen : canreturn;
-                chanbuf.get(b, off, willreturn);
-                available -= willreturn;
-
-                if (marked) { /* copy into markBuf */
-                    try {
-                        markBuf.put (b, off, willreturn);
-                    } catch (BufferOverflowException e) {
-                        marked = false;
-                    }
-                }
-            }
-            return willreturn;
-        }
-
-        public synchronized int available () throws IOException {
-            if (closed)
-                throw new IOException ("Stream is closed");
-
-            if (reset)
-                return markBuf.remaining();
-
-            if (available > 0)
-                return available;
-
-            chanbuf.clear ();
-            available = channel.read (chanbuf);
-            if (available > 0)
-                chanbuf.flip();
-            else if (available == -1)
-                throw new IOException ("Stream is closed");
-            return available;
-        }
-
-        /**
-         * block() only called when available==0 and buf is empty
-         */
-        private synchronized void block () throws IOException {
-            //assert available == 0;
-            int n = selector.select ();
-            //assert n == 1;
-            selector.selectedKeys().clear();
-            available ();
-        }
-
-        public void close () throws IOException {
-            if (closed)
-                return;
-            channel.close ();
-            closed = true;
-        }
-
-        public synchronized void mark (int readlimit) {
-            if (closed)
-                return;
-            this.readlimit = readlimit;
-            markBuf = ByteBuffer.allocate (readlimit);
-            marked = true;
-            reset = false;
-        }
-
-        public synchronized void reset () throws IOException {
-            if (closed )
-                return;
-            if (!marked)
-                throw new IOException ("Stream not marked");
-            marked = false;
-            reset = true;
-            markBuf.flip ();
-        }
-    }
-
-    static class NioOutputStream extends OutputStream {
-        SocketChannel channel;
-        ByteBuffer buf;
-        SelectionKey key;
-        Selector selector;
-        boolean closed;
-        byte[] one;
-
-        public NioOutputStream (SocketChannel channel) throws IOException {
-            this.channel = channel;
-            selector = Selector.open ();
-            key = channel.register (selector, SelectionKey.OP_WRITE);
-            closed = false;
-            one = new byte [1];
-        }
-
-        public synchronized void write (int b) throws IOException {
-            one[0] = (byte)b;
-            write (one, 0, 1);
-        }
-
-        public synchronized void write (byte[] b) throws IOException {
-            write (b, 0, b.length);
-        }
-
-        public synchronized void write (byte[] b, int off, int len) throws IOException {
-            if (closed)
-                throw new IOException ("stream is closed");
-
-            buf = ByteBuffer.allocate (len);
-            buf.put (b, off, len);
-            buf.flip ();
-            int n;
-            while ((n = channel.write (buf)) < len) {
-                len -= n;
-                if (len == 0)
-                    return;
-                selector.select ();
-                selector.selectedKeys().clear ();
-            }
-        }
-
-        public void close () throws IOException {
-            if (closed)
-                return;
-            channel.close ();
-            closed = true;
-        }
-    }
-
-    /**
-     * Utilities for synchronization. A condition is
-     * identified by a string name, and is initialized
-     * upon first use (ie. setCondition() or waitForCondition()). Threads
-     * are blocked until some thread calls (or has called) setCondition() for the same
-     * condition.
-     * <P>
-     * A rendezvous built on a condition is also provided for synchronizing
-     * N threads.
-     */
-
-    private static HashMap conditions = new HashMap();
-
-    /*
-     * Modifiable boolean object
-     */
-    private static class BValue {
-        boolean v;
-    }
-
-    /*
-     * Modifiable int object
-     */
-    private static class IValue {
-        int v;
-        IValue (int i) {
-            v =i;
-        }
-    }
-
-
-    private static BValue getCond (String condition) {
-        synchronized (conditions) {
-            BValue cond = (BValue) conditions.get (condition);
-            if (cond == null) {
-                cond = new BValue();
-                conditions.put (condition, cond);
-            }
-            return cond;
-        }
-    }
-
-    /**
-     * Set the condition to true. Any threads that are currently blocked
-     * waiting on the condition, will be unblocked and allowed to continue.
-     * Threads that subsequently call waitForCondition() will not block.
-     * If the named condition did not exist prior to the call, then it is created
-     * first.
-     */
-
-    public static void setCondition (String condition) {
-        BValue cond = getCond (condition);
-        synchronized (cond) {
-            if (cond.v) {
-                return;
-            }
-            cond.v = true;
-            cond.notifyAll();
-        }
-    }
-
-    /**
-     * If the named condition does not exist, then it is created and initialized
-     * to false. If the condition exists or has just been created and its value
-     * is false, then the thread blocks until another thread sets the condition.
-     * If the condition exists and is already set to true, then this call returns
-     * immediately without blocking.
-     */
-
-    public static void waitForCondition (String condition) {
-        BValue cond = getCond (condition);
-        synchronized (cond) {
-            if (!cond.v) {
-                try {
-                    cond.wait();
-                } catch (InterruptedException e) {}
-            }
-        }
-    }
-
-    /* conditions must be locked when accessing this */
-    static HashMap rv = new HashMap();
-
-    /**
-     * Force N threads to rendezvous (ie. wait for each other) before proceeding.
-     * The first thread(s) to call are blocked until the last
-     * thread makes the call. Then all threads continue.
-     * <p>
-     * All threads that call with the same condition name, must use the same value
-     * for N (or the results may be not be as expected).
-     * <P>
-     * Obviously, if fewer than N threads make the rendezvous then the result
-     * will be a hang.
-     */
-
-    public static void rendezvous (String condition, int N) {
-        BValue cond;
-        IValue iv;
-        String name = "RV_"+condition;
-
-        /* get the condition */
-
-        synchronized (conditions) {
-            cond = (BValue)conditions.get (name);
-            if (cond == null) {
-                /* we are first caller */
-                if (N < 2) {
-                    throw new RuntimeException ("rendezvous must be called with N >= 2");
-                }
-                cond = new BValue ();
-                conditions.put (name, cond);
-                iv = new IValue (N-1);
-                rv.put (name, iv);
-            } else {
-                /* already initialised, just decrement the counter */
-                iv = (IValue) rv.get (name);
-                iv.v --;
-            }
-        }
-
-        if (iv.v > 0) {
-            waitForCondition (name);
-        } else {
-            setCondition (name);
-            synchronized (conditions) {
-                clearCondition (name);
-                rv.remove (name);
-            }
-        }
-    }
-
-    /**
-     * If the named condition exists and is set then remove it, so it can
-     * be re-initialized and used again. If the condition does not exist, or
-     * exists but is not set, then the call returns without doing anything.
-     * Note, some higher level synchronization
-     * may be needed between clear and the other operations.
-     */
-
-    public static void clearCondition(String condition) {
-        BValue cond;
-        synchronized (conditions) {
-            cond = (BValue) conditions.get (condition);
-            if (cond == null) {
-                return;
-            }
-            synchronized (cond) {
-                if (cond.v) {
-                    conditions.remove (condition);
-                }
-            }
-        }
-    }
-}
--- a/test/sun/net/www/httptest/HttpTransaction.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/net/www/httptest/HttpTransaction.java	Wed Sep 26 22:22:51 2012 -0700
@@ -37,7 +37,7 @@
 
     String command;
     URI requesturi;
-    HttpServer.Server server;
+    TestHttpServer.Server server;
     MessageHeader reqheaders, reqtrailers;
     String reqbody;
     byte[] rspbody;
@@ -46,7 +46,7 @@
     int rspbodylen;
     boolean rspchunked;
 
-    HttpTransaction (HttpServer.Server server, String command,
+    HttpTransaction (TestHttpServer.Server server, String command,
                         URI requesturi, MessageHeader headers,
                         String body, MessageHeader trailers, SelectionKey  key) {
         this.command = command;
@@ -290,7 +290,7 @@
      * @param rTag the response string to send with the response code
      */
     public void sendResponse (int rCode, String rTag) throws IOException {
-        OutputStream os = new HttpServer.NioOutputStream(channel());
+        OutputStream os = new TestHttpServer.NioOutputStream(channel());
         PrintStream ps = new PrintStream (os);
         ps.print ("HTTP/1.1 " + rCode + " " + rTag + "\r\n");
         if (rspheaders != null) {
@@ -314,7 +314,7 @@
     /* sends one byte less than intended */
 
     public void sendPartialResponse (int rCode, String rTag)throws IOException {
-        OutputStream os = new HttpServer.NioOutputStream(channel());
+        OutputStream os = new TestHttpServer.NioOutputStream(channel());
         PrintStream ps = new PrintStream (os);
         ps.print ("HTTP/1.1 " + rCode + " " + rTag + "\r\n");
         ps.flush();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/net/www/httptest/TestHttpServer.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,728 @@
+/*
+ * 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
+ * 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.net.*;
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import sun.net.www.MessageHeader;
+import java.util.*;
+
+/**
+ * This class implements a simple HTTP server. It uses multiple threads to
+ * handle connections in parallel, and also multiple connections/requests
+ * can be handled per thread.
+ * <p>
+ * It must be instantiated with a {@link HttpCallback} object to which
+ * requests are given and must be handled.
+ * <p>
+ * Simple synchronization between the client(s) and server can be done
+ * using the {@link #waitForCondition(String)}, {@link #setCondition(String)} and
+ * {@link #rendezvous(String,int)} methods.
+ *
+ * NOTE NOTE NOTE NOTE NOTE NOTE NOTE
+ *
+ * If changes are made here, please sure they are propagated to
+ * the HTTPS equivalent in the JSSE regression test suite.
+ *
+ * NOTE NOTE NOTE NOTE NOTE NOTE NOTE
+ */
+
+public class TestHttpServer {
+
+    ServerSocketChannel schan;
+    int threads;
+    int cperthread;
+    HttpCallback cb;
+    Server[] servers;
+
+    /**
+     * Create a <code>TestHttpServer<code> instance with the specified callback object
+     * for handling requests. One thread is created to handle requests,
+     * and up to ten TCP connections will be handled simultaneously.
+     * @param cb the callback object which is invoked to handle each
+     *  incoming request
+     */
+
+    public TestHttpServer (HttpCallback cb) throws IOException {
+        this (cb, 1, 10, 0);
+    }
+
+    /**
+     * Create a <code>TestHttpServer<code> instance with the specified number of
+     * threads and maximum number of connections per thread. This functions
+     * the same as the 4 arg constructor, where the port argument is set to zero.
+     * @param cb the callback object which is invoked to handle each
+     *     incoming request
+     * @param threads the number of threads to create to handle requests
+     *     in parallel
+     * @param cperthread the number of simultaneous TCP connections to
+     *     handle per thread
+     */
+
+    public TestHttpServer (HttpCallback cb, int threads, int cperthread)
+        throws IOException {
+        this (cb, threads, cperthread, 0);
+    }
+
+    /**
+     * Create a <code>TestHttpServer<code> instance with the specified number
+     * of threads and maximum number of connections per thread and running on
+     * the specified port. The specified number of threads are created to
+     * handle incoming requests, and each thread is allowed
+     * to handle a number of simultaneous TCP connections.
+     * @param cb the callback object which is invoked to handle
+     *  each incoming request
+     * @param threads the number of threads to create to handle
+     *  requests in parallel
+     * @param cperthread the number of simultaneous TCP connections
+     *  to handle per thread
+     * @param port the port number to bind the server to. <code>Zero</code>
+     *  means choose any free port.
+     */
+
+    public TestHttpServer (HttpCallback cb, int threads, int cperthread, int port)
+        throws IOException {
+        schan = ServerSocketChannel.open ();
+        InetSocketAddress addr = new InetSocketAddress (port);
+        schan.socket().bind (addr);
+        this.threads = threads;
+        this.cb = cb;
+        this.cperthread = cperthread;
+        servers = new Server [threads];
+        for (int i=0; i<threads; i++) {
+            servers[i] = new Server (cb, schan, cperthread);
+            servers[i].start();
+        }
+    }
+
+    /** Tell all threads in the server to exit within 5 seconds.
+     *  This is an abortive termination. Just prior to the thread exiting
+     *  all channels in that thread waiting to be closed are forceably closed.
+     */
+
+    public void terminate () {
+        for (int i=0; i<threads; i++) {
+            servers[i].terminate ();
+        }
+    }
+
+    /**
+     * return the local port number to which the server is bound.
+     * @return the local port number
+     */
+
+    public int getLocalPort () {
+        return schan.socket().getLocalPort ();
+    }
+
+    static class Server extends Thread {
+
+        ServerSocketChannel schan;
+        Selector selector;
+        SelectionKey listenerKey;
+        SelectionKey key; /* the current key being processed */
+        HttpCallback cb;
+        ByteBuffer consumeBuffer;
+        int maxconn;
+        int nconn;
+        ClosedChannelList clist;
+        boolean shutdown;
+
+        Server (HttpCallback cb, ServerSocketChannel schan, int maxconn) {
+            this.schan = schan;
+            this.maxconn = maxconn;
+            this.cb = cb;
+            nconn = 0;
+            consumeBuffer = ByteBuffer.allocate (512);
+            clist = new ClosedChannelList ();
+            try {
+                selector = Selector.open ();
+                schan.configureBlocking (false);
+                listenerKey = schan.register (selector, SelectionKey.OP_ACCEPT);
+            } catch (IOException e) {
+                System.err.println ("Server could not start: " + e);
+            }
+        }
+
+        /* Stop the thread as soon as possible */
+        public synchronized void terminate () {
+            shutdown = true;
+        }
+
+        public void run ()  {
+            try {
+                while (true) {
+                    selector.select (1000);
+                    Set selected = selector.selectedKeys();
+                    Iterator iter = selected.iterator();
+                    while (iter.hasNext()) {
+                        key = (SelectionKey)iter.next();
+                        if (key.equals (listenerKey)) {
+                            SocketChannel sock = schan.accept ();
+                            if (sock == null) {
+                                /* false notification */
+                                iter.remove();
+                                continue;
+                            }
+                            sock.configureBlocking (false);
+                            sock.register (selector, SelectionKey.OP_READ);
+                            nconn ++;
+                            System.out.println("SERVER: new connection. chan[" + sock + "]");
+                            if (nconn == maxconn) {
+                                /* deregister */
+                                listenerKey.cancel ();
+                                listenerKey = null;
+                            }
+                        } else {
+                            if (key.isReadable()) {
+                                boolean closed;
+                                SocketChannel chan = (SocketChannel) key.channel();
+                                System.out.println("SERVER: connection readable. chan[" + chan + "]");
+                                if (key.attachment() != null) {
+                                    System.out.println("Server: comsume");
+                                    closed = consume (chan);
+                                } else {
+                                    closed = read (chan, key);
+                                }
+                                if (closed) {
+                                    chan.close ();
+                                    key.cancel ();
+                                    if (nconn == maxconn) {
+                                        listenerKey = schan.register (selector, SelectionKey.OP_ACCEPT);
+                                    }
+                                    nconn --;
+                                }
+                            }
+                        }
+                        iter.remove();
+                    }
+                    clist.check();
+                    if (shutdown) {
+                        clist.terminate ();
+                        return;
+                    }
+                }
+            } catch (IOException e) {
+                System.out.println ("Server exception: " + e);
+                // TODO finish
+            }
+        }
+
+        /* read all the data off the channel without looking at it
+             * return true if connection closed
+             */
+        boolean consume (SocketChannel chan) {
+            try {
+                consumeBuffer.clear ();
+                int c = chan.read (consumeBuffer);
+                if (c == -1)
+                    return true;
+            } catch (IOException e) {
+                return true;
+            }
+            return false;
+        }
+
+        /* return true if the connection is closed, false otherwise */
+
+        private boolean read (SocketChannel chan, SelectionKey key) {
+            HttpTransaction msg;
+            boolean res;
+            try {
+                InputStream is = new BufferedInputStream (new NioInputStream (chan));
+                String requestline = readLine (is);
+                MessageHeader mhead = new MessageHeader (is);
+                String clen = mhead.findValue ("Content-Length");
+                String trferenc = mhead.findValue ("Transfer-Encoding");
+                String data = null;
+                if (trferenc != null && trferenc.equals ("chunked"))
+                    data = new String (readChunkedData (is));
+                else if (clen != null)
+                    data = new String (readNormalData (is, Integer.parseInt (clen)));
+                String[] req = requestline.split (" ");
+                if (req.length < 2) {
+                    /* invalid request line */
+                    return false;
+                }
+                String cmd = req[0];
+                URI uri = null;
+                try {
+                    uri = new URI (req[1]);
+                    msg = new HttpTransaction (this, cmd, uri, mhead, data, null, key);
+                    cb.request (msg);
+                } catch (URISyntaxException e) {
+                    System.err.println ("Invalid URI: " + e);
+                    msg = new HttpTransaction (this, cmd, null, null, null, null, key);
+                    msg.sendResponse (501, "Whatever");
+                }
+                res = false;
+            } catch (IOException e) {
+                res = true;
+            }
+            return res;
+        }
+
+        byte[] readNormalData (InputStream is, int len) throws IOException {
+            byte [] buf  = new byte [len];
+            int c, off=0, remain=len;
+            while (remain > 0 && ((c=is.read (buf, off, remain))>0)) {
+                remain -= c;
+                off += c;
+            }
+            return buf;
+        }
+
+        private void readCRLF(InputStream is) throws IOException {
+            int cr = is.read();
+            int lf = is.read();
+
+            if (((cr & 0xff) != 0x0d) ||
+                ((lf & 0xff) != 0x0a)) {
+                throw new IOException(
+                    "Expected <CR><LF>:  got '" + cr + "/" + lf + "'");
+            }
+        }
+
+        byte[] readChunkedData (InputStream is) throws IOException {
+            LinkedList l = new LinkedList ();
+            int total = 0;
+            for (int len=readChunkLen(is); len!=0; len=readChunkLen(is)) {
+                l.add (readNormalData(is, len));
+                total += len;
+                readCRLF(is);  // CRLF at end of chunk
+            }
+            readCRLF(is); // CRLF at end of Chunked Stream.
+            byte[] buf = new byte [total];
+            Iterator i = l.iterator();
+            int x = 0;
+            while (i.hasNext()) {
+                byte[] b = (byte[])i.next();
+                System.arraycopy (b, 0, buf, x, b.length);
+                x += b.length;
+            }
+            return buf;
+        }
+
+        private int readChunkLen (InputStream is) throws IOException {
+            int c, len=0;
+            boolean done=false, readCR=false;
+            while (!done) {
+                c = is.read ();
+                if (c == '\n' && readCR) {
+                    done = true;
+                } else {
+                    if (c == '\r' && !readCR) {
+                        readCR = true;
+                    } else {
+                        int x=0;
+                        if (c >= 'a' && c <= 'f') {
+                            x = c - 'a' + 10;
+                        } else if (c >= 'A' && c <= 'F') {
+                            x = c - 'A' + 10;
+                        } else if (c >= '0' && c <= '9') {
+                            x = c - '0';
+                        }
+                        len = len * 16 + x;
+                    }
+                }
+            }
+            return len;
+        }
+
+        private String readLine (InputStream is) throws IOException {
+            boolean done=false, readCR=false;
+            byte[] b = new byte [512];
+            int c, l = 0;
+
+            while (!done) {
+                c = is.read ();
+                if (c == '\n' && readCR) {
+                    done = true;
+                } else {
+                    if (c == '\r' && !readCR) {
+                        readCR = true;
+                    } else {
+                        b[l++] = (byte)c;
+                    }
+                }
+            }
+            return new String (b);
+        }
+
+        /** close the channel associated with the current key by:
+         * 1. shutdownOutput (send a FIN)
+         * 2. mark the key so that incoming data is to be consumed and discarded
+         * 3. After a period, close the socket
+         */
+
+        synchronized void orderlyCloseChannel (SelectionKey key) throws IOException {
+            SocketChannel ch = (SocketChannel)key.channel ();
+            System.out.println("SERVER: orderlyCloseChannel chan[" + ch + "]");
+            ch.socket().shutdownOutput();
+            key.attach (this);
+            clist.add (key);
+        }
+
+        synchronized void abortiveCloseChannel (SelectionKey key) throws IOException {
+            SocketChannel ch = (SocketChannel)key.channel ();
+            System.out.println("SERVER: abortiveCloseChannel chan[" + ch + "]");
+
+            Socket s = ch.socket ();
+            s.setSoLinger (true, 0);
+            ch.close();
+        }
+    }
+
+
+    /**
+     * Implements blocking reading semantics on top of a non-blocking channel
+     */
+
+    static class NioInputStream extends InputStream {
+        SocketChannel channel;
+        Selector selector;
+        ByteBuffer chanbuf;
+        SelectionKey key;
+        int available;
+        byte[] one;
+        boolean closed;
+        ByteBuffer markBuf; /* reads may be satisifed from this buffer */
+        boolean marked;
+        boolean reset;
+        int readlimit;
+
+        public NioInputStream (SocketChannel chan) throws IOException {
+            this.channel = chan;
+            selector = Selector.open();
+            chanbuf = ByteBuffer.allocate (1024);
+            key = chan.register (selector, SelectionKey.OP_READ);
+            available = 0;
+            one = new byte[1];
+            closed = marked = reset = false;
+        }
+
+        public synchronized int read (byte[] b) throws IOException {
+            return read (b, 0, b.length);
+        }
+
+        public synchronized int read () throws IOException {
+            return read (one, 0, 1);
+        }
+
+        public synchronized int read (byte[] b, int off, int srclen) throws IOException {
+
+            int canreturn, willreturn;
+
+            if (closed)
+                return -1;
+
+            if (reset) { /* satisfy from markBuf */
+                canreturn = markBuf.remaining ();
+                willreturn = canreturn>srclen ? srclen : canreturn;
+                markBuf.get(b, off, willreturn);
+                if (canreturn == willreturn) {
+                    reset = false;
+                }
+            } else { /* satisfy from channel */
+                canreturn = available();
+                if (canreturn == 0) {
+                    block ();
+                    canreturn = available();
+                }
+                willreturn = canreturn>srclen ? srclen : canreturn;
+                chanbuf.get(b, off, willreturn);
+                available -= willreturn;
+
+                if (marked) { /* copy into markBuf */
+                    try {
+                        markBuf.put (b, off, willreturn);
+                    } catch (BufferOverflowException e) {
+                        marked = false;
+                    }
+                }
+            }
+            return willreturn;
+        }
+
+        public synchronized int available () throws IOException {
+            if (closed)
+                throw new IOException ("Stream is closed");
+
+            if (reset)
+                return markBuf.remaining();
+
+            if (available > 0)
+                return available;
+
+            chanbuf.clear ();
+            available = channel.read (chanbuf);
+            if (available > 0)
+                chanbuf.flip();
+            else if (available == -1)
+                throw new IOException ("Stream is closed");
+            return available;
+        }
+
+        /**
+         * block() only called when available==0 and buf is empty
+         */
+        private synchronized void block () throws IOException {
+            //assert available == 0;
+            int n = selector.select ();
+            //assert n == 1;
+            selector.selectedKeys().clear();
+            available ();
+        }
+
+        public void close () throws IOException {
+            if (closed)
+                return;
+            channel.close ();
+            closed = true;
+        }
+
+        public synchronized void mark (int readlimit) {
+            if (closed)
+                return;
+            this.readlimit = readlimit;
+            markBuf = ByteBuffer.allocate (readlimit);
+            marked = true;
+            reset = false;
+        }
+
+        public synchronized void reset () throws IOException {
+            if (closed )
+                return;
+            if (!marked)
+                throw new IOException ("Stream not marked");
+            marked = false;
+            reset = true;
+            markBuf.flip ();
+        }
+    }
+
+    static class NioOutputStream extends OutputStream {
+        SocketChannel channel;
+        ByteBuffer buf;
+        SelectionKey key;
+        Selector selector;
+        boolean closed;
+        byte[] one;
+
+        public NioOutputStream (SocketChannel channel) throws IOException {
+            this.channel = channel;
+            selector = Selector.open ();
+            key = channel.register (selector, SelectionKey.OP_WRITE);
+            closed = false;
+            one = new byte [1];
+        }
+
+        public synchronized void write (int b) throws IOException {
+            one[0] = (byte)b;
+            write (one, 0, 1);
+        }
+
+        public synchronized void write (byte[] b) throws IOException {
+            write (b, 0, b.length);
+        }
+
+        public synchronized void write (byte[] b, int off, int len) throws IOException {
+            if (closed)
+                throw new IOException ("stream is closed");
+
+            buf = ByteBuffer.allocate (len);
+            buf.put (b, off, len);
+            buf.flip ();
+            int n;
+            while ((n = channel.write (buf)) < len) {
+                len -= n;
+                if (len == 0)
+                    return;
+                selector.select ();
+                selector.selectedKeys().clear ();
+            }
+        }
+
+        public void close () throws IOException {
+            if (closed)
+                return;
+            channel.close ();
+            closed = true;
+        }
+    }
+
+    /**
+     * Utilities for synchronization. A condition is
+     * identified by a string name, and is initialized
+     * upon first use (ie. setCondition() or waitForCondition()). Threads
+     * are blocked until some thread calls (or has called) setCondition() for the same
+     * condition.
+     * <P>
+     * A rendezvous built on a condition is also provided for synchronizing
+     * N threads.
+     */
+
+    private static HashMap conditions = new HashMap();
+
+    /*
+     * Modifiable boolean object
+     */
+    private static class BValue {
+        boolean v;
+    }
+
+    /*
+     * Modifiable int object
+     */
+    private static class IValue {
+        int v;
+        IValue (int i) {
+            v =i;
+        }
+    }
+
+
+    private static BValue getCond (String condition) {
+        synchronized (conditions) {
+            BValue cond = (BValue) conditions.get (condition);
+            if (cond == null) {
+                cond = new BValue();
+                conditions.put (condition, cond);
+            }
+            return cond;
+        }
+    }
+
+    /**
+     * Set the condition to true. Any threads that are currently blocked
+     * waiting on the condition, will be unblocked and allowed to continue.
+     * Threads that subsequently call waitForCondition() will not block.
+     * If the named condition did not exist prior to the call, then it is created
+     * first.
+     */
+
+    public static void setCondition (String condition) {
+        BValue cond = getCond (condition);
+        synchronized (cond) {
+            if (cond.v) {
+                return;
+            }
+            cond.v = true;
+            cond.notifyAll();
+        }
+    }
+
+    /**
+     * If the named condition does not exist, then it is created and initialized
+     * to false. If the condition exists or has just been created and its value
+     * is false, then the thread blocks until another thread sets the condition.
+     * If the condition exists and is already set to true, then this call returns
+     * immediately without blocking.
+     */
+
+    public static void waitForCondition (String condition) {
+        BValue cond = getCond (condition);
+        synchronized (cond) {
+            if (!cond.v) {
+                try {
+                    cond.wait();
+                } catch (InterruptedException e) {}
+            }
+        }
+    }
+
+    /* conditions must be locked when accessing this */
+    static HashMap rv = new HashMap();
+
+    /**
+     * Force N threads to rendezvous (ie. wait for each other) before proceeding.
+     * The first thread(s) to call are blocked until the last
+     * thread makes the call. Then all threads continue.
+     * <p>
+     * All threads that call with the same condition name, must use the same value
+     * for N (or the results may be not be as expected).
+     * <P>
+     * Obviously, if fewer than N threads make the rendezvous then the result
+     * will be a hang.
+     */
+
+    public static void rendezvous (String condition, int N) {
+        BValue cond;
+        IValue iv;
+        String name = "RV_"+condition;
+
+        /* get the condition */
+
+        synchronized (conditions) {
+            cond = (BValue)conditions.get (name);
+            if (cond == null) {
+                /* we are first caller */
+                if (N < 2) {
+                    throw new RuntimeException ("rendezvous must be called with N >= 2");
+                }
+                cond = new BValue ();
+                conditions.put (name, cond);
+                iv = new IValue (N-1);
+                rv.put (name, iv);
+            } else {
+                /* already initialised, just decrement the counter */
+                iv = (IValue) rv.get (name);
+                iv.v --;
+            }
+        }
+
+        if (iv.v > 0) {
+            waitForCondition (name);
+        } else {
+            setCondition (name);
+            synchronized (conditions) {
+                clearCondition (name);
+                rv.remove (name);
+            }
+        }
+    }
+
+    /**
+     * If the named condition exists and is set then remove it, so it can
+     * be re-initialized and used again. If the condition does not exist, or
+     * exists but is not set, then the call returns without doing anything.
+     * Note, some higher level synchronization
+     * may be needed between clear and the other operations.
+     */
+
+    public static void clearCondition(String condition) {
+        BValue cond;
+        synchronized (conditions) {
+            cond = (BValue) conditions.get (condition);
+            if (cond == null) {
+                return;
+            }
+            synchronized (cond) {
+                if (cond.v) {
+                    conditions.remove (condition);
+                }
+            }
+        }
+    }
+}
--- a/test/sun/net/www/protocol/http/B6296310.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/net/www/protocol/http/B6296310.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 6296310
  * @library ../../httptest/
- * @build HttpCallback HttpServer HttpTransaction
+ * @build HttpCallback TestHttpServer HttpTransaction
  * @run main/othervm B6296310
  * @summary  REGRESSION: AppletClassLoader.getResourceAsStream() behaviour is wrong in some cases
  */
@@ -42,7 +42,7 @@
 public class B6296310
 {
    static SimpleHttpTransaction httpTrans;
-   static HttpServer server;
+   static TestHttpServer server;
 
    public static void main(String[] args)
    {
@@ -55,7 +55,7 @@
    public static void startHttpServer() {
       try {
          httpTrans = new SimpleHttpTransaction();
-         server = new HttpServer(httpTrans, 1, 10, 0);
+         server = new TestHttpServer(httpTrans, 1, 10, 0);
       } catch (IOException e) {
          e.printStackTrace();
       }
--- a/test/sun/net/www/protocol/http/B6299712.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/net/www/protocol/http/B6299712.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 6299712
  * @library ../../httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
+ * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main/othervm B6299712
  * @summary  NullPointerException in sun.net.www.protocol.http.HttpURLConnection.followRedirect
  */
@@ -49,7 +49,7 @@
  */
 public class B6299712 {
     static SimpleHttpTransaction httpTrans;
-    static HttpServer server;
+    static TestHttpServer server;
 
     public static void main(String[] args) throws Exception {
         ResponseCache.setDefault(new DeployCacheHandler());
@@ -61,7 +61,7 @@
     public static void startHttpServer() {
         try {
             httpTrans = new SimpleHttpTransaction();
-            server = new HttpServer(httpTrans, 1, 10, 0);
+            server = new TestHttpServer(httpTrans, 1, 10, 0);
         } catch (IOException e) {
             e.printStackTrace();
         }
--- a/test/sun/net/www/protocol/http/RelativeRedirect.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/net/www/protocol/http/RelativeRedirect.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 4726087
  * @library ../../httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
+ * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main RelativeRedirect
  * @summary URLConnection cannot handle redirects
  */
@@ -35,7 +35,7 @@
 
 public class RelativeRedirect implements HttpCallback {
     static int count = 0;
-    static HttpServer server;
+    static TestHttpServer server;
 
     static class MyAuthenticator extends Authenticator {
         public MyAuthenticator () {
@@ -89,7 +89,7 @@
         MyAuthenticator auth = new MyAuthenticator ();
         Authenticator.setDefault (auth);
         try {
-            server = new HttpServer (new RelativeRedirect(), 1, 10, 0);
+            server = new TestHttpServer (new RelativeRedirect(), 1, 10, 0);
             System.out.println ("Server: listening on port: " + server.getLocalPort());
             URL url = new URL("http://localhost:"+server.getLocalPort());
             System.out.println ("client opening connection to: " + url);
--- a/test/sun/net/www/protocol/http/ResponseCacheStream.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/net/www/protocol/http/ResponseCacheStream.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 6262486
  * @library ../../httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
+ * @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main/othervm -Dhttp.keepAlive=false ResponseCacheStream
  * @summary COMPATIBILITY: jagex_com - Monkey Puzzle applet fails to load
  */
@@ -91,13 +91,13 @@
         }
     }
 
-    static HttpServer server;
+    static TestHttpServer server;
 
     public static void main(String[] args) throws Exception {
         MyResponseCache cache = new MyResponseCache();
         try {
             ResponseCache.setDefault(cache);
-            server = new HttpServer (new ResponseCacheStream());
+            server = new TestHttpServer (new ResponseCacheStream());
             System.out.println ("Server: listening on port: " + server.getLocalPort());
             URL url = new URL ("http://127.0.0.1:"+server.getLocalPort()+"/");
             System.out.println ("Client: connecting to " + url);
--- a/test/sun/net/www/protocol/http/SetChunkedStreamingMode.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/net/www/protocol/http/SetChunkedStreamingMode.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 5049976
  * @library ../../httptest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction
+  @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
  * @run main SetChunkedStreamingMode
  * @summary Unspecified NPE is thrown when streaming output mode is enabled
  */
@@ -60,11 +60,11 @@
         System.out.println ("finished reading");
     }
 
-    static HttpServer server;
+    static TestHttpServer server;
 
     public static void main (String[] args) throws Exception {
         try {
-            server = new HttpServer (new SetChunkedStreamingMode(), 1, 10, 0);
+            server = new TestHttpServer (new SetChunkedStreamingMode(), 1, 10, 0);
             System.out.println ("Server: listening on port: " + server.getLocalPort());
             URL url = new URL ("http://127.0.0.1:"+server.getLocalPort()+"/");
             System.out.println ("Client: connecting to " + url);
--- a/test/sun/security/ssl/sun/net/www/http/ChunkedOutputStream/Test.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/security/ssl/sun/net/www/http/ChunkedOutputStream/Test.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,6 +25,7 @@
  * @test
  * @bug 5026745
  * @library ../../httpstest/
+ * @build TestHttpsServer HttpCallback
  * @run main/othervm Test
  *
  *     SunJSSE does not support dynamic system properties, no way to re-use
@@ -275,7 +276,7 @@
         }
     }
 
-    static HttpServer server;
+    static TestHttpsServer server;
 
     public static void main (String[] args) throws Exception {
         // setup properties to do ssl
@@ -296,7 +297,7 @@
             HttpsURLConnection.setDefaultHostnameVerifier(new NameVerifier());
 
             try {
-                server = new HttpServer (new Test(), 1, 10, 0);
+                server = new TestHttpsServer (new Test(), 1, 10, 0);
                 System.out.println ("Server started: listening on port: " + server.getLocalPort());
                 // the test server doesn't support keep-alive yet
                 // test1("http://localhost:"+server.getLocalPort()+"/d0");
--- a/test/sun/security/ssl/sun/net/www/httpstest/HttpServer.java	Fri Sep 21 12:22:52 2012 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,933 +0,0 @@
-/*
- * Copyright (c) 2002, 2004, Oracle and/or its affiliates. All rights reserved.
- * 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.net.*;
-import java.io.*;
-import java.nio.*;
-import java.nio.channels.*;
-import sun.net.www.MessageHeader;
-import java.util.*;
-import javax.net.ssl.*;
-import javax.net.ssl.SSLEngineResult.*;
-import java.security.*;
-
-/**
- * This class implements a simple HTTPS server. It uses multiple threads to
- * handle connections in parallel, and will spin off a new thread to handle
- * each request. (this is easier to implement with SSLEngine)
- * <p>
- * It must be instantiated with a {@link HttpCallback} object to which
- * requests are given and must be handled.
- * <p>
- * Simple synchronization between the client(s) and server can be done
- * using the {@link #waitForCondition(String)}, {@link #setCondition(String)} and
- * {@link #rendezvous(String,int)} methods.
- *
- * NOTE NOTE NOTE NOTE NOTE NOTE NOTE
- *
- * If you make a change in here, please don't forget to make the
- * corresponding change in the J2SE equivalent.
- *
- * NOTE NOTE NOTE NOTE NOTE NOTE NOTE
- */
-
-public class HttpServer {
-
-    ServerSocketChannel schan;
-    int threads;
-    int cperthread;
-    HttpCallback cb;
-    Server[] servers;
-
-    // ssl related fields
-    static SSLContext sslCtx;
-
-    /**
-     * Create a <code>HttpServer<code> instance with the specified callback object
-     * for handling requests. One thread is created to handle requests,
-     * and up to ten TCP connections will be handled simultaneously.
-     * @param cb the callback object which is invoked to handle each
-     *  incoming request
-     */
-
-    public HttpServer (HttpCallback cb) throws IOException {
-        this (cb, 1, 10, 0);
-    }
-
-    /**
-     * Create a <code>HttpServer<code> instance with the specified number of
-     * threads and maximum number of connections per thread. This functions
-     * the same as the 4 arg constructor, where the port argument is set to zero.
-     * @param cb the callback object which is invoked to handle each
-     *     incoming request
-     * @param threads the number of threads to create to handle requests
-     *     in parallel
-     * @param cperthread the number of simultaneous TCP connections to
-     *     handle per thread
-     */
-
-    public HttpServer (HttpCallback cb, int threads, int cperthread)
-        throws IOException {
-        this (cb, threads, cperthread, 0);
-    }
-
-    /**
-     * Create a <code>HttpServer<code> instance with the specified number
-     * of threads and maximum number of connections per thread and running on
-     * the specified port. The specified number of threads are created to
-     * handle incoming requests, and each thread is allowed
-     * to handle a number of simultaneous TCP connections.
-     * @param cb the callback object which is invoked to handle
-     *  each incoming request
-     * @param threads the number of threads to create to handle
-     *  requests in parallel
-     * @param cperthread the number of simultaneous TCP connections
-     *  to handle per thread
-     * @param port the port number to bind the server to. <code>Zero</code>
-     *  means choose any free port.
-     */
-
-    public HttpServer (HttpCallback cb, int threads, int cperthread, int port)
-        throws IOException {
-        schan = ServerSocketChannel.open ();
-        InetSocketAddress addr = new InetSocketAddress (port);
-        schan.socket().bind (addr);
-        this.threads = threads;
-        this.cb = cb;
-        this.cperthread = cperthread;
-
-        try {
-            // create and initialize a SSLContext
-            KeyStore ks = KeyStore.getInstance("JKS");
-            KeyStore ts = KeyStore.getInstance("JKS");
-            char[] passphrase = "passphrase".toCharArray();
-
-            ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), passphrase);
-            ts.load(new FileInputStream(System.getProperty("javax.net.ssl.trustStore")), passphrase);
-
-            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
-            kmf.init(ks, passphrase);
-
-            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
-            tmf.init(ts);
-
-            sslCtx = SSLContext.getInstance("TLS");
-
-            sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
-
-            servers = new Server [threads];
-            for (int i=0; i<threads; i++) {
-                servers[i] = new Server (cb, schan, cperthread);
-                servers[i].start();
-            }
-        } catch (Exception ex) {
-            throw new RuntimeException("test failed. cause: "+ex.getMessage());
-        }
-    }
-
-    /** Tell all threads in the server to exit within 5 seconds.
-     *  This is an abortive termination. Just prior to the thread exiting
-     *  all channels in that thread waiting to be closed are forceably closed.
-     */
-
-    public void terminate () {
-        for (int i=0; i<threads; i++) {
-            servers[i].terminate ();
-        }
-    }
-
-    /**
-     * return the local port number to which the server is bound.
-     * @return the local port number
-     */
-
-    public int getLocalPort () {
-        return schan.socket().getLocalPort ();
-    }
-
-    static class Server extends Thread {
-
-        ServerSocketChannel schan;
-        Selector selector;
-        SelectionKey listenerKey;
-        SelectionKey key; /* the current key being processed */
-        HttpCallback cb;
-        ByteBuffer consumeBuffer;
-        int maxconn;
-        int nconn;
-        ClosedChannelList clist;
-        boolean shutdown;
-
-        Server (HttpCallback cb, ServerSocketChannel schan, int maxconn) {
-            this.schan = schan;
-            this.maxconn = maxconn;
-            this.cb = cb;
-            nconn = 0;
-            consumeBuffer = ByteBuffer.allocate (512);
-            clist = new ClosedChannelList ();
-            try {
-                selector = Selector.open ();
-                schan.configureBlocking (false);
-                listenerKey = schan.register (selector, SelectionKey.OP_ACCEPT);
-            } catch (IOException e) {
-                System.err.println ("Server could not start: " + e);
-            }
-        }
-
-        /* Stop the thread as soon as possible */
-        public synchronized void terminate () {
-            shutdown = true;
-        }
-
-        public void run ()  {
-            try {
-                while (true) {
-                    selector.select (1000);
-                    Set selected = selector.selectedKeys();
-                    Iterator iter = selected.iterator();
-                    while (iter.hasNext()) {
-                        key = (SelectionKey)iter.next();
-                        if (key.equals (listenerKey)) {
-                            SocketChannel sock = schan.accept ();
-                            if (sock == null) {
-                                /* false notification */
-                                iter.remove();
-                                continue;
-                            }
-                            sock.configureBlocking (true);
-                            SSLEngine sslEng = sslCtx.createSSLEngine();
-                            sslEng.setUseClientMode(false);
-                            new ServerWorker(cb, sock, sslEng).start();
-                            nconn ++;
-                            if (nconn == maxconn) {
-                                /* deregister */
-                                listenerKey.cancel ();
-                                listenerKey = null;
-                            }
-                        } else {
-                            if (key.isReadable()) {
-                                boolean closed = false;
-                                SocketChannel chan = (SocketChannel) key.channel();
-                                if (key.attachment() != null) {
-                                    closed = consume (chan);
-                                }
-
-                                if (closed) {
-                                    chan.close ();
-                                    key.cancel ();
-                                    if (nconn == maxconn) {
-                                        listenerKey = schan.register (selector, SelectionKey.OP_ACCEPT);
-                                    }
-                                    nconn --;
-                                }
-                            }
-                        }
-                        iter.remove();
-                    }
-                    clist.check();
-
-                    synchronized (this) {
-                        if (shutdown) {
-                            clist.terminate ();
-                            return;
-                        }
-                    }
-                }
-            } catch (IOException e) {
-                System.out.println ("Server exception: " + e);
-                // TODO finish
-            }
-        }
-
-        /* read all the data off the channel without looking at it
-             * return true if connection closed
-             */
-        boolean consume (SocketChannel chan) {
-            try {
-                consumeBuffer.clear ();
-                int c = chan.read (consumeBuffer);
-                if (c == -1)
-                    return true;
-            } catch (IOException e) {
-                return true;
-            }
-            return false;
-        }
-    }
-
-    static class ServerWorker extends Thread {
-        private ByteBuffer inNetBB;
-        private ByteBuffer outNetBB;
-        private ByteBuffer inAppBB;
-        private ByteBuffer outAppBB;
-
-        SSLEngine sslEng;
-        SocketChannel schan;
-        HttpCallback cb;
-        HandshakeStatus currentHSStatus;
-        boolean initialHSComplete;
-        /*
-         * All inbound data goes through this buffer.
-         *
-         * It might be nice to use a cache of ByteBuffers so we're
-         * not alloc/dealloc'ing all over the place.
-         */
-
-        /*
-         * Application buffers, also used for handshaking
-         */
-        private int appBBSize;
-
-        ServerWorker (HttpCallback cb, SocketChannel schan, SSLEngine sslEng) {
-            this.sslEng = sslEng;
-            this.schan = schan;
-            this.cb = cb;
-            currentHSStatus = HandshakeStatus.NEED_UNWRAP;
-            initialHSComplete = false;
-            int netBBSize = sslEng.getSession().getPacketBufferSize();
-            inNetBB =  ByteBuffer.allocate(netBBSize);
-            outNetBB = ByteBuffer.allocate(netBBSize);
-            appBBSize = sslEng.getSession().getApplicationBufferSize();
-            inAppBB = ByteBuffer.allocate(appBBSize);
-            outAppBB = ByteBuffer.allocate(appBBSize);
-        }
-
-        public SSLEngine getSSLEngine() {
-            return sslEng;
-        }
-
-        public ByteBuffer outNetBB() {
-            return outNetBB;
-        }
-
-        public ByteBuffer outAppBB() {
-            return outAppBB;
-        }
-
-        public void run () {
-            try {
-                SSLEngineResult result;
-
-                while (!initialHSComplete) {
-
-                    switch (currentHSStatus) {
-
-                    case NEED_UNWRAP:
-                        int bytes = schan.read(inNetBB);
-
-needIO:
-                        while (currentHSStatus == HandshakeStatus.NEED_UNWRAP) {
-                            /*
-                             * Don't need to resize requestBB, since no app data should
-                             * be generated here.
-                             */
-                            inNetBB.flip();
-                            result = sslEng.unwrap(inNetBB, inAppBB);
-                            inNetBB.compact();
-                            currentHSStatus = result.getHandshakeStatus();
-
-                            switch (result.getStatus()) {
-
-                            case OK:
-                                switch (currentHSStatus) {
-                                case NOT_HANDSHAKING:
-                                    throw new IOException(
-                                                          "Not handshaking during initial handshake");
-
-                                case NEED_TASK:
-                                    Runnable task;
-                                    while ((task = sslEng.getDelegatedTask()) != null) {
-                                        task.run();
-                                        currentHSStatus = sslEng.getHandshakeStatus();
-                                    }
-                                    break;
-                                }
-
-                                break;
-
-                            case BUFFER_UNDERFLOW:
-                                break needIO;
-
-                            default: // BUFFER_OVERFLOW/CLOSED:
-                                throw new IOException("Received" + result.getStatus() +
-                                                      "during initial handshaking");
-                            }
-                        }
-
-                        /*
-                         * Just transitioned from read to write.
-                         */
-                        if (currentHSStatus != HandshakeStatus.NEED_WRAP) {
-                            break;
-                        }
-
-                        // Fall through and fill the write buffer.
-
-                    case NEED_WRAP:
-                        /*
-                         * The flush above guarantees the out buffer to be empty
-                         */
-                        outNetBB.clear();
-                        result = sslEng.wrap(inAppBB, outNetBB);
-                        outNetBB.flip();
-                        schan.write (outNetBB);
-                        outNetBB.compact();
-                        currentHSStatus = result.getHandshakeStatus();
-
-                        switch (result.getStatus()) {
-                        case OK:
-
-                            if (currentHSStatus == HandshakeStatus.NEED_TASK) {
-                                Runnable task;
-                                while ((task = sslEng.getDelegatedTask()) != null) {
-                                    task.run();
-                                    currentHSStatus = sslEng.getHandshakeStatus();
-                                }
-                            }
-
-                            break;
-
-                        default: // BUFFER_OVERFLOW/BUFFER_UNDERFLOW/CLOSED:
-                            throw new IOException("Received" + result.getStatus() +
-                                                  "during initial handshaking");
-                        }
-                        break;
-
-                    case FINISHED:
-                        initialHSComplete = true;
-                        break;
-                    default: // NOT_HANDSHAKING/NEED_TASK
-                        throw new RuntimeException("Invalid Handshaking State" +
-                                                   currentHSStatus);
-                    } // switch
-                }
-                // read the application data; using non-blocking mode
-                schan.configureBlocking(false);
-                read(schan, sslEng);
-            } catch (Exception ex) {
-                throw new RuntimeException(ex);
-            }
-        }
-
-        /* return true if the connection is closed, false otherwise */
-
-        private boolean read (SocketChannel chan, SSLEngine sslEng) {
-            HttpTransaction msg;
-            boolean res;
-            try {
-                InputStream is = new BufferedInputStream (new NioInputStream (chan, sslEng, inNetBB, inAppBB));
-                String requestline = readLine (is);
-                MessageHeader mhead = new MessageHeader (is);
-                String clen = mhead.findValue ("Content-Length");
-                String trferenc = mhead.findValue ("Transfer-Encoding");
-                String data = null;
-                if (trferenc != null && trferenc.equals ("chunked"))
-                    data = new String (readChunkedData (is));
-                else if (clen != null)
-                    data = new String (readNormalData (is, Integer.parseInt (clen)));
-                String[] req = requestline.split (" ");
-                if (req.length < 2) {
-                    /* invalid request line */
-                    return false;
-                }
-                String cmd = req[0];
-                URI uri = null;
-                try {
-                    uri = new URI (req[1]);
-                    msg = new HttpTransaction (this, cmd, uri, mhead, data, null, chan);
-                    cb.request (msg);
-                } catch (URISyntaxException e) {
-                    System.err.println ("Invalid URI: " + e);
-                    msg = new HttpTransaction (this, cmd, null, null, null, null, chan);
-                    msg.sendResponse (501, "Whatever");
-                }
-                res = false;
-            } catch (IOException e) {
-                res = true;
-            }
-            return res;
-        }
-
-        byte[] readNormalData (InputStream is, int len) throws IOException {
-            byte [] buf  = new byte [len];
-            int c, off=0, remain=len;
-            while (remain > 0 && ((c=is.read (buf, off, remain))>0)) {
-                remain -= c;
-                off += c;
-            }
-            return buf;
-        }
-
-        private void readCRLF(InputStream is) throws IOException {
-            int cr = is.read();
-            int lf = is.read();
-
-            if (((cr & 0xff) != 0x0d) ||
-                ((lf & 0xff) != 0x0a)) {
-                throw new IOException(
-                    "Expected <CR><LF>:  got '" + cr + "/" + lf + "'");
-            }
-        }
-
-        byte[] readChunkedData (InputStream is) throws IOException {
-            LinkedList l = new LinkedList ();
-            int total = 0;
-            for (int len=readChunkLen(is); len!=0; len=readChunkLen(is)) {
-                l.add (readNormalData(is, len));
-                total += len;
-                readCRLF(is); // CRLF at end of chunk
-            }
-            readCRLF(is); // CRLF at end of Chunked Stream.
-            byte[] buf = new byte [total];
-            Iterator i = l.iterator();
-            int x = 0;
-            while (i.hasNext()) {
-                byte[] b = (byte[])i.next();
-                System.arraycopy (b, 0, buf, x, b.length);
-                x += b.length;
-            }
-            return buf;
-        }
-
-        private int readChunkLen (InputStream is) throws IOException {
-            int c, len=0;
-            boolean done=false, readCR=false;
-            while (!done) {
-                c = is.read ();
-                if (c == '\n' && readCR) {
-                    done = true;
-                } else {
-                    if (c == '\r' && !readCR) {
-                        readCR = true;
-                    } else {
-                        int x=0;
-                        if (c >= 'a' && c <= 'f') {
-                            x = c - 'a' + 10;
-                        } else if (c >= 'A' && c <= 'F') {
-                            x = c - 'A' + 10;
-                        } else if (c >= '0' && c <= '9') {
-                            x = c - '0';
-                        }
-                        len = len * 16 + x;
-                    }
-                }
-            }
-            return len;
-        }
-
-        private String readLine (InputStream is) throws IOException {
-            boolean done=false, readCR=false;
-            byte[] b = new byte [512];
-            int c, l = 0;
-
-            while (!done) {
-                c = is.read ();
-                if (c == '\n' && readCR) {
-                    done = true;
-                } else {
-                    if (c == '\r' && !readCR) {
-                        readCR = true;
-                    } else {
-                        b[l++] = (byte)c;
-                    }
-                }
-            }
-            return new String (b);
-        }
-
-        /** close the channel associated with the current key by:
-         * 1. shutdownOutput (send a FIN)
-         * 2. mark the key so that incoming data is to be consumed and discarded
-         * 3. After a period, close the socket
-         */
-
-        synchronized void orderlyCloseChannel (SocketChannel ch) throws IOException {
-            ch.socket().shutdownOutput();
-        }
-
-        synchronized void abortiveCloseChannel (SocketChannel ch) throws IOException {
-            Socket s = ch.socket ();
-            s.setSoLinger (true, 0);
-            ch.close();
-        }
-    }
-
-
-    /**
-     * Implements blocking reading semantics on top of a non-blocking channel
-     */
-
-    static class NioInputStream extends InputStream {
-        SSLEngine sslEng;
-        SocketChannel channel;
-        Selector selector;
-        ByteBuffer inNetBB;
-        ByteBuffer inAppBB;
-        SelectionKey key;
-        int available;
-        byte[] one;
-        boolean closed;
-        ByteBuffer markBuf; /* reads may be satisifed from this buffer */
-        boolean marked;
-        boolean reset;
-        int readlimit;
-
-        public NioInputStream (SocketChannel chan, SSLEngine sslEng, ByteBuffer inNetBB, ByteBuffer inAppBB) throws IOException {
-            this.sslEng = sslEng;
-            this.channel = chan;
-            selector = Selector.open();
-            this.inNetBB = inNetBB;
-            this.inAppBB = inAppBB;
-            key = chan.register (selector, SelectionKey.OP_READ);
-            available = 0;
-            one = new byte[1];
-            closed = marked = reset = false;
-        }
-
-        public synchronized int read (byte[] b) throws IOException {
-            return read (b, 0, b.length);
-        }
-
-        public synchronized int read () throws IOException {
-            return read (one, 0, 1);
-        }
-
-        public synchronized int read (byte[] b, int off, int srclen) throws IOException {
-
-            int canreturn, willreturn;
-
-            if (closed)
-                return -1;
-
-            if (reset) { /* satisfy from markBuf */
-                canreturn = markBuf.remaining ();
-                willreturn = canreturn>srclen ? srclen : canreturn;
-                markBuf.get(b, off, willreturn);
-                if (canreturn == willreturn) {
-                    reset = false;
-                }
-            } else { /* satisfy from channel */
-                canreturn = available();
-                if (canreturn == 0) {
-                    block ();
-                    canreturn = available();
-                }
-                willreturn = canreturn>srclen ? srclen : canreturn;
-                inAppBB.get(b, off, willreturn);
-                available -= willreturn;
-
-                if (marked) { /* copy into markBuf */
-                    try {
-                        markBuf.put (b, off, willreturn);
-                    } catch (BufferOverflowException e) {
-                        marked = false;
-                    }
-                }
-            }
-            return willreturn;
-        }
-
-        public synchronized int available () throws IOException {
-            if (closed)
-                throw new IOException ("Stream is closed");
-
-            if (reset)
-                return markBuf.remaining();
-
-            if (available > 0)
-                return available;
-
-            inAppBB.clear ();
-            int bytes = channel.read (inNetBB);
-
-            int needed = sslEng.getSession().getApplicationBufferSize();
-            if (needed > inAppBB.remaining()) {
-                inAppBB = ByteBuffer.allocate(needed);
-            }
-            inNetBB.flip();
-            SSLEngineResult result = sslEng.unwrap(inNetBB, inAppBB);
-            inNetBB.compact();
-            available = result.bytesProduced();
-
-            if (available > 0)
-                inAppBB.flip();
-            else if (available == -1)
-                throw new IOException ("Stream is closed");
-            return available;
-        }
-
-        /**
-         * block() only called when available==0 and buf is empty
-         */
-        private synchronized void block () throws IOException {
-            //assert available == 0;
-            int n = selector.select ();
-            //assert n == 1;
-            selector.selectedKeys().clear();
-            available ();
-        }
-
-        public void close () throws IOException {
-            if (closed)
-                return;
-            channel.close ();
-            closed = true;
-        }
-
-        public synchronized void mark (int readlimit) {
-            if (closed)
-                return;
-            this.readlimit = readlimit;
-            markBuf = ByteBuffer.allocate (readlimit);
-            marked = true;
-            reset = false;
-        }
-
-        public synchronized void reset () throws IOException {
-            if (closed )
-                return;
-            if (!marked)
-                throw new IOException ("Stream not marked");
-            marked = false;
-            reset = true;
-            markBuf.flip ();
-        }
-    }
-
-    static class NioOutputStream extends OutputStream {
-        SSLEngine sslEng;
-        SocketChannel channel;
-        ByteBuffer outNetBB;
-        ByteBuffer outAppBB;
-        SelectionKey key;
-        Selector selector;
-        boolean closed;
-        byte[] one;
-
-        public NioOutputStream (SocketChannel channel, SSLEngine sslEng, ByteBuffer outNetBB, ByteBuffer outAppBB) throws IOException {
-            this.sslEng = sslEng;
-            this.channel = channel;
-            this.outNetBB = outNetBB;
-            this.outAppBB = outAppBB;
-            selector = Selector.open ();
-            key = channel.register (selector, SelectionKey.OP_WRITE);
-            closed = false;
-            one = new byte [1];
-        }
-
-        public synchronized void write (int b) throws IOException {
-            one[0] = (byte)b;
-            write (one, 0, 1);
-        }
-
-        public synchronized void write (byte[] b) throws IOException {
-            write (b, 0, b.length);
-        }
-
-        public synchronized void write (byte[] b, int off, int len) throws IOException {
-            if (closed)
-                throw new IOException ("stream is closed");
-
-            outAppBB = ByteBuffer.allocate (len);
-            outAppBB.put (b, off, len);
-            outAppBB.flip ();
-            int n;
-            outNetBB.clear();
-            int needed = sslEng.getSession().getPacketBufferSize();
-            if (outNetBB.capacity() < needed) {
-                outNetBB = ByteBuffer.allocate(needed);
-            }
-            SSLEngineResult ret = sslEng.wrap(outAppBB, outNetBB);
-            outNetBB.flip();
-            int newLen = ret.bytesProduced();
-            while ((n = channel.write (outNetBB)) < newLen) {
-                newLen -= n;
-                if (newLen == 0)
-                    return;
-                selector.select ();
-                selector.selectedKeys().clear ();
-            }
-        }
-
-        public void close () throws IOException {
-            if (closed)
-                return;
-            channel.close ();
-            closed = true;
-        }
-    }
-
-    /**
-     * Utilities for synchronization. A condition is
-     * identified by a string name, and is initialized
-     * upon first use (ie. setCondition() or waitForCondition()). Threads
-     * are blocked until some thread calls (or has called) setCondition() for the same
-     * condition.
-     * <P>
-     * A rendezvous built on a condition is also provided for synchronizing
-     * N threads.
-     */
-
-    private static HashMap conditions = new HashMap();
-
-    /*
-     * Modifiable boolean object
-     */
-    private static class BValue {
-        boolean v;
-    }
-
-    /*
-     * Modifiable int object
-     */
-    private static class IValue {
-        int v;
-        IValue (int i) {
-            v =i;
-        }
-    }
-
-
-    private static BValue getCond (String condition) {
-        synchronized (conditions) {
-            BValue cond = (BValue) conditions.get (condition);
-            if (cond == null) {
-                cond = new BValue();
-                conditions.put (condition, cond);
-            }
-            return cond;
-        }
-    }
-
-    /**
-     * Set the condition to true. Any threads that are currently blocked
-     * waiting on the condition, will be unblocked and allowed to continue.
-     * Threads that subsequently call waitForCondition() will not block.
-     * If the named condition did not exist prior to the call, then it is created
-     * first.
-     */
-
-    public static void setCondition (String condition) {
-        BValue cond = getCond (condition);
-        synchronized (cond) {
-            if (cond.v) {
-                return;
-            }
-            cond.v = true;
-            cond.notifyAll();
-        }
-    }
-
-    /**
-     * If the named condition does not exist, then it is created and initialized
-     * to false. If the condition exists or has just been created and its value
-     * is false, then the thread blocks until another thread sets the condition.
-     * If the condition exists and is already set to true, then this call returns
-     * immediately without blocking.
-     */
-
-    public static void waitForCondition (String condition) {
-        BValue cond = getCond (condition);
-        synchronized (cond) {
-            if (!cond.v) {
-                try {
-                    cond.wait();
-                } catch (InterruptedException e) {}
-            }
-        }
-    }
-
-    /* conditions must be locked when accessing this */
-    static HashMap rv = new HashMap();
-
-    /**
-     * Force N threads to rendezvous (ie. wait for each other) before proceeding.
-     * The first thread(s) to call are blocked until the last
-     * thread makes the call. Then all threads continue.
-     * <p>
-     * All threads that call with the same condition name, must use the same value
-     * for N (or the results may be not be as expected).
-     * <P>
-     * Obviously, if fewer than N threads make the rendezvous then the result
-     * will be a hang.
-     */
-
-    public static void rendezvous (String condition, int N) {
-        BValue cond;
-        IValue iv;
-        String name = "RV_"+condition;
-
-        /* get the condition */
-
-        synchronized (conditions) {
-            cond = (BValue)conditions.get (name);
-            if (cond == null) {
-                /* we are first caller */
-                if (N < 2) {
-                    throw new RuntimeException ("rendezvous must be called with N >= 2");
-                }
-                cond = new BValue ();
-                conditions.put (name, cond);
-                iv = new IValue (N-1);
-                rv.put (name, iv);
-            } else {
-                /* already initialised, just decrement the counter */
-                iv = (IValue) rv.get (name);
-                iv.v --;
-            }
-        }
-
-        if (iv.v > 0) {
-            waitForCondition (name);
-        } else {
-            setCondition (name);
-            synchronized (conditions) {
-                clearCondition (name);
-                rv.remove (name);
-            }
-        }
-    }
-
-    /**
-     * If the named condition exists and is set then remove it, so it can
-     * be re-initialized and used again. If the condition does not exist, or
-     * exists but is not set, then the call returns without doing anything.
-     * Note, some higher level synchronization
-     * may be needed between clear and the other operations.
-     */
-
-    public static void clearCondition(String condition) {
-        BValue cond;
-        synchronized (conditions) {
-            cond = (BValue) conditions.get (condition);
-            if (cond == null) {
-                return;
-            }
-            synchronized (cond) {
-                if (cond.v) {
-                    conditions.remove (condition);
-                }
-            }
-        }
-    }
-}
--- a/test/sun/security/ssl/sun/net/www/httpstest/HttpTransaction.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/security/ssl/sun/net/www/httpstest/HttpTransaction.java	Wed Sep 26 22:22:51 2012 -0700
@@ -37,7 +37,7 @@
 
     String command;
     URI requesturi;
-    HttpServer.ServerWorker server;
+    TestHttpsServer.ServerWorker server;
     MessageHeader reqheaders, reqtrailers;
     String reqbody;
     byte[] rspbody;
@@ -46,7 +46,7 @@
     int rspbodylen;
     boolean rspchunked;
 
-    HttpTransaction (HttpServer.ServerWorker server, String command,
+    HttpTransaction (TestHttpsServer.ServerWorker server, String command,
                         URI requesturi, MessageHeader headers,
                         String body, MessageHeader trailers, SocketChannel ch) {
         this.command = command;
@@ -290,7 +290,7 @@
      * @param rTag the response string to send with the response code
      */
     public void sendResponse (int rCode, String rTag) throws IOException {
-        OutputStream os = new HttpServer.NioOutputStream(channel(), server.getSSLEngine(), server.outNetBB(), server.outAppBB());
+        OutputStream os = new TestHttpsServer.NioOutputStream(channel(), server.getSSLEngine(), server.outNetBB(), server.outAppBB());
         PrintStream ps = new PrintStream (os);
         ps.print ("HTTP/1.1 " + rCode + " " + rTag + "\r\n");
         if (rspheaders != null) {
@@ -314,7 +314,7 @@
     /* sends one byte less than intended */
 
     public void sendPartialResponse (int rCode, String rTag)throws IOException {
-        OutputStream os = new HttpServer.NioOutputStream(channel(), server.getSSLEngine(), server.outNetBB(), server.outAppBB());
+        OutputStream os = new TestHttpsServer.NioOutputStream(channel(), server.getSSLEngine(), server.outNetBB(), server.outAppBB());
         PrintStream ps = new PrintStream (os);
         ps.print ("HTTP/1.1 " + rCode + " " + rTag + "\r\n");
         ps.flush();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/ssl/sun/net/www/httpstest/TestHttpsServer.java	Wed Sep 26 22:22:51 2012 -0700
@@ -0,0 +1,933 @@
+/*
+ * Copyright (c) 2002, 2004, Oracle and/or its affiliates. All rights reserved.
+ * 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.net.*;
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import sun.net.www.MessageHeader;
+import java.util.*;
+import javax.net.ssl.*;
+import javax.net.ssl.SSLEngineResult.*;
+import java.security.*;
+
+/**
+ * This class implements a simple HTTPS server. It uses multiple threads to
+ * handle connections in parallel, and will spin off a new thread to handle
+ * each request. (this is easier to implement with SSLEngine)
+ * <p>
+ * It must be instantiated with a {@link HttpCallback} object to which
+ * requests are given and must be handled.
+ * <p>
+ * Simple synchronization between the client(s) and server can be done
+ * using the {@link #waitForCondition(String)}, {@link #setCondition(String)} and
+ * {@link #rendezvous(String,int)} methods.
+ *
+ * NOTE NOTE NOTE NOTE NOTE NOTE NOTE
+ *
+ * If you make a change in here, please don't forget to make the
+ * corresponding change in the J2SE equivalent.
+ *
+ * NOTE NOTE NOTE NOTE NOTE NOTE NOTE
+ */
+
+public class TestHttpsServer {
+
+    ServerSocketChannel schan;
+    int threads;
+    int cperthread;
+    HttpCallback cb;
+    Server[] servers;
+
+    // ssl related fields
+    static SSLContext sslCtx;
+
+    /**
+     * Create a <code>TestHttpsServer<code> instance with the specified callback object
+     * for handling requests. One thread is created to handle requests,
+     * and up to ten TCP connections will be handled simultaneously.
+     * @param cb the callback object which is invoked to handle each
+     *  incoming request
+     */
+
+    public TestHttpsServer (HttpCallback cb) throws IOException {
+        this (cb, 1, 10, 0);
+    }
+
+    /**
+     * Create a <code>TestHttpsServer<code> instance with the specified number of
+     * threads and maximum number of connections per thread. This functions
+     * the same as the 4 arg constructor, where the port argument is set to zero.
+     * @param cb the callback object which is invoked to handle each
+     *     incoming request
+     * @param threads the number of threads to create to handle requests
+     *     in parallel
+     * @param cperthread the number of simultaneous TCP connections to
+     *     handle per thread
+     */
+
+    public TestHttpsServer (HttpCallback cb, int threads, int cperthread)
+        throws IOException {
+        this (cb, threads, cperthread, 0);
+    }
+
+    /**
+     * Create a <code>TestHttpsServer<code> instance with the specified number
+     * of threads and maximum number of connections per thread and running on
+     * the specified port. The specified number of threads are created to
+     * handle incoming requests, and each thread is allowed
+     * to handle a number of simultaneous TCP connections.
+     * @param cb the callback object which is invoked to handle
+     *  each incoming request
+     * @param threads the number of threads to create to handle
+     *  requests in parallel
+     * @param cperthread the number of simultaneous TCP connections
+     *  to handle per thread
+     * @param port the port number to bind the server to. <code>Zero</code>
+     *  means choose any free port.
+     */
+
+    public TestHttpsServer (HttpCallback cb, int threads, int cperthread, int port)
+        throws IOException {
+        schan = ServerSocketChannel.open ();
+        InetSocketAddress addr = new InetSocketAddress (port);
+        schan.socket().bind (addr);
+        this.threads = threads;
+        this.cb = cb;
+        this.cperthread = cperthread;
+
+        try {
+            // create and initialize a SSLContext
+            KeyStore ks = KeyStore.getInstance("JKS");
+            KeyStore ts = KeyStore.getInstance("JKS");
+            char[] passphrase = "passphrase".toCharArray();
+
+            ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), passphrase);
+            ts.load(new FileInputStream(System.getProperty("javax.net.ssl.trustStore")), passphrase);
+
+            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
+            kmf.init(ks, passphrase);
+
+            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
+            tmf.init(ts);
+
+            sslCtx = SSLContext.getInstance("TLS");
+
+            sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+
+            servers = new Server [threads];
+            for (int i=0; i<threads; i++) {
+                servers[i] = new Server (cb, schan, cperthread);
+                servers[i].start();
+            }
+        } catch (Exception ex) {
+            throw new RuntimeException("test failed. cause: "+ex.getMessage());
+        }
+    }
+
+    /** Tell all threads in the server to exit within 5 seconds.
+     *  This is an abortive termination. Just prior to the thread exiting
+     *  all channels in that thread waiting to be closed are forceably closed.
+     */
+
+    public void terminate () {
+        for (int i=0; i<threads; i++) {
+            servers[i].terminate ();
+        }
+    }
+
+    /**
+     * return the local port number to which the server is bound.
+     * @return the local port number
+     */
+
+    public int getLocalPort () {
+        return schan.socket().getLocalPort ();
+    }
+
+    static class Server extends Thread {
+
+        ServerSocketChannel schan;
+        Selector selector;
+        SelectionKey listenerKey;
+        SelectionKey key; /* the current key being processed */
+        HttpCallback cb;
+        ByteBuffer consumeBuffer;
+        int maxconn;
+        int nconn;
+        ClosedChannelList clist;
+        boolean shutdown;
+
+        Server (HttpCallback cb, ServerSocketChannel schan, int maxconn) {
+            this.schan = schan;
+            this.maxconn = maxconn;
+            this.cb = cb;
+            nconn = 0;
+            consumeBuffer = ByteBuffer.allocate (512);
+            clist = new ClosedChannelList ();
+            try {
+                selector = Selector.open ();
+                schan.configureBlocking (false);
+                listenerKey = schan.register (selector, SelectionKey.OP_ACCEPT);
+            } catch (IOException e) {
+                System.err.println ("Server could not start: " + e);
+            }
+        }
+
+        /* Stop the thread as soon as possible */
+        public synchronized void terminate () {
+            shutdown = true;
+        }
+
+        public void run ()  {
+            try {
+                while (true) {
+                    selector.select (1000);
+                    Set selected = selector.selectedKeys();
+                    Iterator iter = selected.iterator();
+                    while (iter.hasNext()) {
+                        key = (SelectionKey)iter.next();
+                        if (key.equals (listenerKey)) {
+                            SocketChannel sock = schan.accept ();
+                            if (sock == null) {
+                                /* false notification */
+                                iter.remove();
+                                continue;
+                            }
+                            sock.configureBlocking (true);
+                            SSLEngine sslEng = sslCtx.createSSLEngine();
+                            sslEng.setUseClientMode(false);
+                            new ServerWorker(cb, sock, sslEng).start();
+                            nconn ++;
+                            if (nconn == maxconn) {
+                                /* deregister */
+                                listenerKey.cancel ();
+                                listenerKey = null;
+                            }
+                        } else {
+                            if (key.isReadable()) {
+                                boolean closed = false;
+                                SocketChannel chan = (SocketChannel) key.channel();
+                                if (key.attachment() != null) {
+                                    closed = consume (chan);
+                                }
+
+                                if (closed) {
+                                    chan.close ();
+                                    key.cancel ();
+                                    if (nconn == maxconn) {
+                                        listenerKey = schan.register (selector, SelectionKey.OP_ACCEPT);
+                                    }
+                                    nconn --;
+                                }
+                            }
+                        }
+                        iter.remove();
+                    }
+                    clist.check();
+
+                    synchronized (this) {
+                        if (shutdown) {
+                            clist.terminate ();
+                            return;
+                        }
+                    }
+                }
+            } catch (IOException e) {
+                System.out.println ("Server exception: " + e);
+                // TODO finish
+            }
+        }
+
+        /* read all the data off the channel without looking at it
+             * return true if connection closed
+             */
+        boolean consume (SocketChannel chan) {
+            try {
+                consumeBuffer.clear ();
+                int c = chan.read (consumeBuffer);
+                if (c == -1)
+                    return true;
+            } catch (IOException e) {
+                return true;
+            }
+            return false;
+        }
+    }
+
+    static class ServerWorker extends Thread {
+        private ByteBuffer inNetBB;
+        private ByteBuffer outNetBB;
+        private ByteBuffer inAppBB;
+        private ByteBuffer outAppBB;
+
+        SSLEngine sslEng;
+        SocketChannel schan;
+        HttpCallback cb;
+        HandshakeStatus currentHSStatus;
+        boolean initialHSComplete;
+        /*
+         * All inbound data goes through this buffer.
+         *
+         * It might be nice to use a cache of ByteBuffers so we're
+         * not alloc/dealloc'ing all over the place.
+         */
+
+        /*
+         * Application buffers, also used for handshaking
+         */
+        private int appBBSize;
+
+        ServerWorker (HttpCallback cb, SocketChannel schan, SSLEngine sslEng) {
+            this.sslEng = sslEng;
+            this.schan = schan;
+            this.cb = cb;
+            currentHSStatus = HandshakeStatus.NEED_UNWRAP;
+            initialHSComplete = false;
+            int netBBSize = sslEng.getSession().getPacketBufferSize();
+            inNetBB =  ByteBuffer.allocate(netBBSize);
+            outNetBB = ByteBuffer.allocate(netBBSize);
+            appBBSize = sslEng.getSession().getApplicationBufferSize();
+            inAppBB = ByteBuffer.allocate(appBBSize);
+            outAppBB = ByteBuffer.allocate(appBBSize);
+        }
+
+        public SSLEngine getSSLEngine() {
+            return sslEng;
+        }
+
+        public ByteBuffer outNetBB() {
+            return outNetBB;
+        }
+
+        public ByteBuffer outAppBB() {
+            return outAppBB;
+        }
+
+        public void run () {
+            try {
+                SSLEngineResult result;
+
+                while (!initialHSComplete) {
+
+                    switch (currentHSStatus) {
+
+                    case NEED_UNWRAP:
+                        int bytes = schan.read(inNetBB);
+
+needIO:
+                        while (currentHSStatus == HandshakeStatus.NEED_UNWRAP) {
+                            /*
+                             * Don't need to resize requestBB, since no app data should
+                             * be generated here.
+                             */
+                            inNetBB.flip();
+                            result = sslEng.unwrap(inNetBB, inAppBB);
+                            inNetBB.compact();
+                            currentHSStatus = result.getHandshakeStatus();
+
+                            switch (result.getStatus()) {
+
+                            case OK:
+                                switch (currentHSStatus) {
+                                case NOT_HANDSHAKING:
+                                    throw new IOException(
+                                                          "Not handshaking during initial handshake");
+
+                                case NEED_TASK:
+                                    Runnable task;
+                                    while ((task = sslEng.getDelegatedTask()) != null) {
+                                        task.run();
+                                        currentHSStatus = sslEng.getHandshakeStatus();
+                                    }
+                                    break;
+                                }
+
+                                break;
+
+                            case BUFFER_UNDERFLOW:
+                                break needIO;
+
+                            default: // BUFFER_OVERFLOW/CLOSED:
+                                throw new IOException("Received" + result.getStatus() +
+                                                      "during initial handshaking");
+                            }
+                        }
+
+                        /*
+                         * Just transitioned from read to write.
+                         */
+                        if (currentHSStatus != HandshakeStatus.NEED_WRAP) {
+                            break;
+                        }
+
+                        // Fall through and fill the write buffer.
+
+                    case NEED_WRAP:
+                        /*
+                         * The flush above guarantees the out buffer to be empty
+                         */
+                        outNetBB.clear();
+                        result = sslEng.wrap(inAppBB, outNetBB);
+                        outNetBB.flip();
+                        schan.write (outNetBB);
+                        outNetBB.compact();
+                        currentHSStatus = result.getHandshakeStatus();
+
+                        switch (result.getStatus()) {
+                        case OK:
+
+                            if (currentHSStatus == HandshakeStatus.NEED_TASK) {
+                                Runnable task;
+                                while ((task = sslEng.getDelegatedTask()) != null) {
+                                    task.run();
+                                    currentHSStatus = sslEng.getHandshakeStatus();
+                                }
+                            }
+
+                            break;
+
+                        default: // BUFFER_OVERFLOW/BUFFER_UNDERFLOW/CLOSED:
+                            throw new IOException("Received" + result.getStatus() +
+                                                  "during initial handshaking");
+                        }
+                        break;
+
+                    case FINISHED:
+                        initialHSComplete = true;
+                        break;
+                    default: // NOT_HANDSHAKING/NEED_TASK
+                        throw new RuntimeException("Invalid Handshaking State" +
+                                                   currentHSStatus);
+                    } // switch
+                }
+                // read the application data; using non-blocking mode
+                schan.configureBlocking(false);
+                read(schan, sslEng);
+            } catch (Exception ex) {
+                throw new RuntimeException(ex);
+            }
+        }
+
+        /* return true if the connection is closed, false otherwise */
+
+        private boolean read (SocketChannel chan, SSLEngine sslEng) {
+            HttpTransaction msg;
+            boolean res;
+            try {
+                InputStream is = new BufferedInputStream (new NioInputStream (chan, sslEng, inNetBB, inAppBB));
+                String requestline = readLine (is);
+                MessageHeader mhead = new MessageHeader (is);
+                String clen = mhead.findValue ("Content-Length");
+                String trferenc = mhead.findValue ("Transfer-Encoding");
+                String data = null;
+                if (trferenc != null && trferenc.equals ("chunked"))
+                    data = new String (readChunkedData (is));
+                else if (clen != null)
+                    data = new String (readNormalData (is, Integer.parseInt (clen)));
+                String[] req = requestline.split (" ");
+                if (req.length < 2) {
+                    /* invalid request line */
+                    return false;
+                }
+                String cmd = req[0];
+                URI uri = null;
+                try {
+                    uri = new URI (req[1]);
+                    msg = new HttpTransaction (this, cmd, uri, mhead, data, null, chan);
+                    cb.request (msg);
+                } catch (URISyntaxException e) {
+                    System.err.println ("Invalid URI: " + e);
+                    msg = new HttpTransaction (this, cmd, null, null, null, null, chan);
+                    msg.sendResponse (501, "Whatever");
+                }
+                res = false;
+            } catch (IOException e) {
+                res = true;
+            }
+            return res;
+        }
+
+        byte[] readNormalData (InputStream is, int len) throws IOException {
+            byte [] buf  = new byte [len];
+            int c, off=0, remain=len;
+            while (remain > 0 && ((c=is.read (buf, off, remain))>0)) {
+                remain -= c;
+                off += c;
+            }
+            return buf;
+        }
+
+        private void readCRLF(InputStream is) throws IOException {
+            int cr = is.read();
+            int lf = is.read();
+
+            if (((cr & 0xff) != 0x0d) ||
+                ((lf & 0xff) != 0x0a)) {
+                throw new IOException(
+                    "Expected <CR><LF>:  got '" + cr + "/" + lf + "'");
+            }
+        }
+
+        byte[] readChunkedData (InputStream is) throws IOException {
+            LinkedList l = new LinkedList ();
+            int total = 0;
+            for (int len=readChunkLen(is); len!=0; len=readChunkLen(is)) {
+                l.add (readNormalData(is, len));
+                total += len;
+                readCRLF(is); // CRLF at end of chunk
+            }
+            readCRLF(is); // CRLF at end of Chunked Stream.
+            byte[] buf = new byte [total];
+            Iterator i = l.iterator();
+            int x = 0;
+            while (i.hasNext()) {
+                byte[] b = (byte[])i.next();
+                System.arraycopy (b, 0, buf, x, b.length);
+                x += b.length;
+            }
+            return buf;
+        }
+
+        private int readChunkLen (InputStream is) throws IOException {
+            int c, len=0;
+            boolean done=false, readCR=false;
+            while (!done) {
+                c = is.read ();
+                if (c == '\n' && readCR) {
+                    done = true;
+                } else {
+                    if (c == '\r' && !readCR) {
+                        readCR = true;
+                    } else {
+                        int x=0;
+                        if (c >= 'a' && c <= 'f') {
+                            x = c - 'a' + 10;
+                        } else if (c >= 'A' && c <= 'F') {
+                            x = c - 'A' + 10;
+                        } else if (c >= '0' && c <= '9') {
+                            x = c - '0';
+                        }
+                        len = len * 16 + x;
+                    }
+                }
+            }
+            return len;
+        }
+
+        private String readLine (InputStream is) throws IOException {
+            boolean done=false, readCR=false;
+            byte[] b = new byte [512];
+            int c, l = 0;
+
+            while (!done) {
+                c = is.read ();
+                if (c == '\n' && readCR) {
+                    done = true;
+                } else {
+                    if (c == '\r' && !readCR) {
+                        readCR = true;
+                    } else {
+                        b[l++] = (byte)c;
+                    }
+                }
+            }
+            return new String (b);
+        }
+
+        /** close the channel associated with the current key by:
+         * 1. shutdownOutput (send a FIN)
+         * 2. mark the key so that incoming data is to be consumed and discarded
+         * 3. After a period, close the socket
+         */
+
+        synchronized void orderlyCloseChannel (SocketChannel ch) throws IOException {
+            ch.socket().shutdownOutput();
+        }
+
+        synchronized void abortiveCloseChannel (SocketChannel ch) throws IOException {
+            Socket s = ch.socket ();
+            s.setSoLinger (true, 0);
+            ch.close();
+        }
+    }
+
+
+    /**
+     * Implements blocking reading semantics on top of a non-blocking channel
+     */
+
+    static class NioInputStream extends InputStream {
+        SSLEngine sslEng;
+        SocketChannel channel;
+        Selector selector;
+        ByteBuffer inNetBB;
+        ByteBuffer inAppBB;
+        SelectionKey key;
+        int available;
+        byte[] one;
+        boolean closed;
+        ByteBuffer markBuf; /* reads may be satisifed from this buffer */
+        boolean marked;
+        boolean reset;
+        int readlimit;
+
+        public NioInputStream (SocketChannel chan, SSLEngine sslEng, ByteBuffer inNetBB, ByteBuffer inAppBB) throws IOException {
+            this.sslEng = sslEng;
+            this.channel = chan;
+            selector = Selector.open();
+            this.inNetBB = inNetBB;
+            this.inAppBB = inAppBB;
+            key = chan.register (selector, SelectionKey.OP_READ);
+            available = 0;
+            one = new byte[1];
+            closed = marked = reset = false;
+        }
+
+        public synchronized int read (byte[] b) throws IOException {
+            return read (b, 0, b.length);
+        }
+
+        public synchronized int read () throws IOException {
+            return read (one, 0, 1);
+        }
+
+        public synchronized int read (byte[] b, int off, int srclen) throws IOException {
+
+            int canreturn, willreturn;
+
+            if (closed)
+                return -1;
+
+            if (reset) { /* satisfy from markBuf */
+                canreturn = markBuf.remaining ();
+                willreturn = canreturn>srclen ? srclen : canreturn;
+                markBuf.get(b, off, willreturn);
+                if (canreturn == willreturn) {
+                    reset = false;
+                }
+            } else { /* satisfy from channel */
+                canreturn = available();
+                if (canreturn == 0) {
+                    block ();
+                    canreturn = available();
+                }
+                willreturn = canreturn>srclen ? srclen : canreturn;
+                inAppBB.get(b, off, willreturn);
+                available -= willreturn;
+
+                if (marked) { /* copy into markBuf */
+                    try {
+                        markBuf.put (b, off, willreturn);
+                    } catch (BufferOverflowException e) {
+                        marked = false;
+                    }
+                }
+            }
+            return willreturn;
+        }
+
+        public synchronized int available () throws IOException {
+            if (closed)
+                throw new IOException ("Stream is closed");
+
+            if (reset)
+                return markBuf.remaining();
+
+            if (available > 0)
+                return available;
+
+            inAppBB.clear ();
+            int bytes = channel.read (inNetBB);
+
+            int needed = sslEng.getSession().getApplicationBufferSize();
+            if (needed > inAppBB.remaining()) {
+                inAppBB = ByteBuffer.allocate(needed);
+            }
+            inNetBB.flip();
+            SSLEngineResult result = sslEng.unwrap(inNetBB, inAppBB);
+            inNetBB.compact();
+            available = result.bytesProduced();
+
+            if (available > 0)
+                inAppBB.flip();
+            else if (available == -1)
+                throw new IOException ("Stream is closed");
+            return available;
+        }
+
+        /**
+         * block() only called when available==0 and buf is empty
+         */
+        private synchronized void block () throws IOException {
+            //assert available == 0;
+            int n = selector.select ();
+            //assert n == 1;
+            selector.selectedKeys().clear();
+            available ();
+        }
+
+        public void close () throws IOException {
+            if (closed)
+                return;
+            channel.close ();
+            closed = true;
+        }
+
+        public synchronized void mark (int readlimit) {
+            if (closed)
+                return;
+            this.readlimit = readlimit;
+            markBuf = ByteBuffer.allocate (readlimit);
+            marked = true;
+            reset = false;
+        }
+
+        public synchronized void reset () throws IOException {
+            if (closed )
+                return;
+            if (!marked)
+                throw new IOException ("Stream not marked");
+            marked = false;
+            reset = true;
+            markBuf.flip ();
+        }
+    }
+
+    static class NioOutputStream extends OutputStream {
+        SSLEngine sslEng;
+        SocketChannel channel;
+        ByteBuffer outNetBB;
+        ByteBuffer outAppBB;
+        SelectionKey key;
+        Selector selector;
+        boolean closed;
+        byte[] one;
+
+        public NioOutputStream (SocketChannel channel, SSLEngine sslEng, ByteBuffer outNetBB, ByteBuffer outAppBB) throws IOException {
+            this.sslEng = sslEng;
+            this.channel = channel;
+            this.outNetBB = outNetBB;
+            this.outAppBB = outAppBB;
+            selector = Selector.open ();
+            key = channel.register (selector, SelectionKey.OP_WRITE);
+            closed = false;
+            one = new byte [1];
+        }
+
+        public synchronized void write (int b) throws IOException {
+            one[0] = (byte)b;
+            write (one, 0, 1);
+        }
+
+        public synchronized void write (byte[] b) throws IOException {
+            write (b, 0, b.length);
+        }
+
+        public synchronized void write (byte[] b, int off, int len) throws IOException {
+            if (closed)
+                throw new IOException ("stream is closed");
+
+            outAppBB = ByteBuffer.allocate (len);
+            outAppBB.put (b, off, len);
+            outAppBB.flip ();
+            int n;
+            outNetBB.clear();
+            int needed = sslEng.getSession().getPacketBufferSize();
+            if (outNetBB.capacity() < needed) {
+                outNetBB = ByteBuffer.allocate(needed);
+            }
+            SSLEngineResult ret = sslEng.wrap(outAppBB, outNetBB);
+            outNetBB.flip();
+            int newLen = ret.bytesProduced();
+            while ((n = channel.write (outNetBB)) < newLen) {
+                newLen -= n;
+                if (newLen == 0)
+                    return;
+                selector.select ();
+                selector.selectedKeys().clear ();
+            }
+        }
+
+        public void close () throws IOException {
+            if (closed)
+                return;
+            channel.close ();
+            closed = true;
+        }
+    }
+
+    /**
+     * Utilities for synchronization. A condition is
+     * identified by a string name, and is initialized
+     * upon first use (ie. setCondition() or waitForCondition()). Threads
+     * are blocked until some thread calls (or has called) setCondition() for the same
+     * condition.
+     * <P>
+     * A rendezvous built on a condition is also provided for synchronizing
+     * N threads.
+     */
+
+    private static HashMap conditions = new HashMap();
+
+    /*
+     * Modifiable boolean object
+     */
+    private static class BValue {
+        boolean v;
+    }
+
+    /*
+     * Modifiable int object
+     */
+    private static class IValue {
+        int v;
+        IValue (int i) {
+            v =i;
+        }
+    }
+
+
+    private static BValue getCond (String condition) {
+        synchronized (conditions) {
+            BValue cond = (BValue) conditions.get (condition);
+            if (cond == null) {
+                cond = new BValue();
+                conditions.put (condition, cond);
+            }
+            return cond;
+        }
+    }
+
+    /**
+     * Set the condition to true. Any threads that are currently blocked
+     * waiting on the condition, will be unblocked and allowed to continue.
+     * Threads that subsequently call waitForCondition() will not block.
+     * If the named condition did not exist prior to the call, then it is created
+     * first.
+     */
+
+    public static void setCondition (String condition) {
+        BValue cond = getCond (condition);
+        synchronized (cond) {
+            if (cond.v) {
+                return;
+            }
+            cond.v = true;
+            cond.notifyAll();
+        }
+    }
+
+    /**
+     * If the named condition does not exist, then it is created and initialized
+     * to false. If the condition exists or has just been created and its value
+     * is false, then the thread blocks until another thread sets the condition.
+     * If the condition exists and is already set to true, then this call returns
+     * immediately without blocking.
+     */
+
+    public static void waitForCondition (String condition) {
+        BValue cond = getCond (condition);
+        synchronized (cond) {
+            if (!cond.v) {
+                try {
+                    cond.wait();
+                } catch (InterruptedException e) {}
+            }
+        }
+    }
+
+    /* conditions must be locked when accessing this */
+    static HashMap rv = new HashMap();
+
+    /**
+     * Force N threads to rendezvous (ie. wait for each other) before proceeding.
+     * The first thread(s) to call are blocked until the last
+     * thread makes the call. Then all threads continue.
+     * <p>
+     * All threads that call with the same condition name, must use the same value
+     * for N (or the results may be not be as expected).
+     * <P>
+     * Obviously, if fewer than N threads make the rendezvous then the result
+     * will be a hang.
+     */
+
+    public static void rendezvous (String condition, int N) {
+        BValue cond;
+        IValue iv;
+        String name = "RV_"+condition;
+
+        /* get the condition */
+
+        synchronized (conditions) {
+            cond = (BValue)conditions.get (name);
+            if (cond == null) {
+                /* we are first caller */
+                if (N < 2) {
+                    throw new RuntimeException ("rendezvous must be called with N >= 2");
+                }
+                cond = new BValue ();
+                conditions.put (name, cond);
+                iv = new IValue (N-1);
+                rv.put (name, iv);
+            } else {
+                /* already initialised, just decrement the counter */
+                iv = (IValue) rv.get (name);
+                iv.v --;
+            }
+        }
+
+        if (iv.v > 0) {
+            waitForCondition (name);
+        } else {
+            setCondition (name);
+            synchronized (conditions) {
+                clearCondition (name);
+                rv.remove (name);
+            }
+        }
+    }
+
+    /**
+     * If the named condition exists and is set then remove it, so it can
+     * be re-initialized and used again. If the condition does not exist, or
+     * exists but is not set, then the call returns without doing anything.
+     * Note, some higher level synchronization
+     * may be needed between clear and the other operations.
+     */
+
+    public static void clearCondition(String condition) {
+        BValue cond;
+        synchronized (conditions) {
+            cond = (BValue) conditions.get (condition);
+            if (cond == null) {
+                return;
+            }
+            synchronized (cond) {
+                if (cond.v) {
+                    conditions.remove (condition);
+                }
+            }
+        }
+    }
+}
--- a/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/B6216082.java	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/B6216082.java	Wed Sep 26 22:22:51 2012 -0700
@@ -25,7 +25,7 @@
  * @test
  * @bug 6216082
  * @library ../../../httpstest/
- * @build HttpCallback HttpServer ClosedChannelList HttpTransaction TunnelProxy
+ * @build HttpCallback TestHttpsServer ClosedChannelList HttpTransaction TunnelProxy
  * @summary  Redirect problem with HttpsURLConnection using a proxy
  *     SunJSSE does not support dynamic system properties, no way to re-use
  *     system properties in samevm/agentvm mode.
@@ -39,7 +39,7 @@
 
 public class B6216082 {
     static SimpleHttpTransaction httpTrans;
-    static HttpServer server;
+    static TestHttpsServer server;
     static TunnelProxy proxy;
 
     // it seems there's no proxy ever if a url points to 'localhost',
@@ -133,7 +133,7 @@
         // Both the https server and the proxy let the
         // system pick up an ephemeral port.
         httpTrans = new SimpleHttpTransaction();
-        server = new HttpServer(httpTrans, 1, 10, 0);
+        server = new TestHttpsServer(httpTrans, 1, 10, 0);
         proxy = new TunnelProxy(1, 10, 0);
     }
 
--- a/test/sun/security/tools/keytool/autotest.sh	Fri Sep 21 12:22:52 2012 -0700
+++ b/test/sun/security/tools/keytool/autotest.sh	Wed Sep 26 22:22:51 2012 -0700
@@ -41,30 +41,35 @@
   exit 1
 fi
 
+find_one() {
+  for TARGET_FILE in $@; do
+    if [ -e "$TARGET_FILE" ]; then
+      echo $TARGET_FILE
+      return
+    fi
+  done
+}
+
 # set platform-dependent variables
 OS=`uname -s`
 case "$OS" in
   SunOS )
     FS="/"
-    LIBNAME=libsoftokn3.so
-    ARCH=`isainfo`
-    case "$ARCH" in
-      sparc* )
-        NSSDIR="/usr/lib/mps"
-        ;;
-      * )
-        echo "Will not run test on: Solaris ${ARCH}"
-        exit 0;
-        ;;
-    esac
+    LIBNAME="/usr/lib/mps/libsoftokn3.so"
     ;;
   Linux )
-    LIBNAME=libsoftokn3.so
     ARCH=`uname -m`
     FS="/"
     case "$ARCH" in
       i[3-6]86 )
-        NSSDIR="/usr/lib"
+        LIBNAME=`find_one \
+            "/usr/lib/libsoftokn3.so" \
+            "/usr/lib/i386-linux-gnu/nss/libsoftokn3.so"`
+        ;;
+      x86_64 )
+        LIBNAME=`find_one \
+            "/usr/lib64/libsoftokn3.so" \
+            "/usr/lib/x86_64-linux-gnu/nss/libsoftokn3.so"`
         ;;
       * )
         echo "Will not run test on: Linux ${ARCH}"
@@ -78,7 +83,13 @@
     ;;
 esac
 
-${TESTJAVA}${FS}bin${FS}javac -d . ${TESTSRC}${FS}KeyToolTest.java || exit 10
+if [ "$LIBNAME" = "" ]; then
+  echo "Cannot find LIBNAME"
+  exit 1
+fi
+
+${TESTJAVA}${FS}bin${FS}javac -d . -XDignore.symbol.file \
+        ${TESTSRC}${FS}KeyToolTest.java || exit 10
 
 NSS=${TESTSRC}${FS}..${FS}..${FS}pkcs11${FS}nss
 
@@ -91,7 +102,7 @@
 chmod u+w cert8.db
 
 echo | ${TESTJAVA}${FS}bin${FS}java -Dnss \
-   -Dnss.lib=${NSSDIR}${FS}${LIBNAME} \
+   -Dnss.lib=${LIBNAME} \
    KeyToolTest
 status=$?
 
@@ -105,4 +116,3 @@
 rm TestException.class
 
 exit $status
-